dropdownlistfor无法通过jquery从控制器更改为选定值

时间:2015-12-28 03:33:32

标签: javascript jquery asp.net asp.net-mvc

我已阅读此问题ASP.NET MVC DropDownListFor not selecting value from model并回答,但我不知道解决问题的方法。

这是我的控制器的一部分,这是我第一次为视图调用ddl,但还没有选择任何值。

private void bindDDLRefund(FormModel mod){
    //   refundCodes = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted.Value == false).Select(e => e.RefundCode).FirstOrDefault();
    mod.DdlRefundPercentage = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted.Value == false).ToList().Select(e => new SelectListItem { Text = e.CfPercentage.ToString(), Value = e.RefundCode.ToString() }).OrderBy(e => e.Value);
     //mod.DdlRefundPercentage = _uow.ParameterRefund.GetAll().Where(e => e.IsDeleted == false).ToList().Select(e => new SelectListItem() { Text = e.CfPercentage.ToString(), Value = e.RefundCode.ToString(), Selected = (e.RefundCode == mod.RefundCode) }).ToList();

}

public ActionResult Add(){
    var mod = new FormModel();
    //var percentage = GetAllPercentage();
    //mod.ddlRefundPercentage = GetSelectListItems(percentage);
    bindDDLRefund(mod);
    mod.isCreate = true;

    return View("Form",mod);
}

然后,这里是从控制器中选择的值

public JsonResult GetTicketData(string ticketnumber){
    bool isSuccess = false;
    var result = new spRefTicketRefundRetrieve();

    int isError = 0;
    string errorDesc = "";
    var mod = new FormModel();

    try{
        spRefTicketRefundRetrieveHeader obj = _uow.StoreProc.spRefTicketRefundRetrieve(ticketnumber);
        isError = obj.IsError;
        errorDesc = obj.ErrorDesc;
        if (obj.IsError == 0){
            result = obj.detailData;
        }
        isSuccess = true;
    }
    catch (Exception ex){
        Logger.LogError("Reload Ticket Data", "Id = " + ticketnumber, ex);
    }

    return Json(new { success = isSuccess, value = result, isError = isError, errorDesc = errorDesc  }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
        public JsonResult GetRefundData(string refund_id)
        {
            bool isSuccess = false;
            var result = new spRefTicketRefundDetail();

            int refundId = Encryption.Decrypt(refund_id);
            try
            {
                result = _uow.StoreProc.spRefTicketRefundDetail(refundId);                

                isSuccess = true;
            }
            catch (Exception ex)
            {
                Logger.LogError("Reload Refund Data", "Id = " + refundId, ex);
            }

            return Json(new { success = isSuccess, value = result }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetCFData(string ticketNumber, string refundCode)
        {
            bool isSuccess = false;
            var result = new spRefTicketRefundChangeCF();
            int isError = 0;
            string errorDesc = "";
            try
            {
                spRefTicketRefundChangeCFHeader obj = _uow.StoreProc.spRefTicketRefundChangeCF(ticketNumber, refundCode);
                isError = obj.IsError;
                errorDesc = obj.ErrorDesc;

                if (obj.IsError == 0)
                {
                    result = obj.listData;
                }
                isSuccess = true;
            }
            catch (Exception ex)
            {
                Logger.LogError("Reload CF Data", "Id = " + ticketNumber, ex);
            }

            return Json(new { success = isSuccess, value = result, isError = isError, errorDesc = errorDesc }, JsonRequestBehavior.AllowGet);
        }

所选值约为CfPercentage,变量result包含CF_PERCENTAGE,代表CfPercentage,

这是我的观点和jQuery;

@Html.DropDownListFor(e => e.RefundCode, Model.DdlRefundPercentage, new { @class = "form-control", id= "ddl-refund",onchange="CFChange();" })



   var GetRefundData = function (refundId) {
            $.ajax({
                url: '@Url.Action("GetRefundData")',
                type: 'POST',
                data: { refund_id: refundId },
                success: function (result) {
                    console.log(result);
                    if (result.success) {
                        SetFormDetail(result.value);                        
                    }
                    else
                    {
                    }
                },
                error: function (result) {
                    alert('Something error occured, please refresh the page.')
                }
            });
        };



     var GetRefundViewData = function (refundId) {
                $.ajax({
                    url: '@Url.Action("GetRefundData")',
                    type: 'POST',
                    data: { refund_id: refundId },
                    success: function (result) {
                        console.log(result);
                        if (result.success) {
                            SetFormView(result.value);
                        }
                        else {
                        }
                    },
                    error: function (result) {
                        alert('Something error occured, please refresh the page.')
                    }
                });
            };

var GetTicketData = function (ticketNumber) {
        var target = $("#loading");
        $.ajax({
            beforeSend: function () {
                target.html('<img src="@Url.Content("~/Content/images/ajax-loader.gif")"> loading...');
                $('#divForm').css('display', 'none');
            },
            url: '@Url.Action("GetTicketData")',
            type: 'POST',
            data: { ticketnumber: ticketNumber },
            success: function (result) {
                console.log(result);
                if (result.success) {
                    target.html('');
                    if (result.isError == "0") {
                        $('#divForm').css('display', 'block');
                        $('#txtHiddenTicketNumber').val(ticketNumber);
                        SetForm(result.value);

                        GetCFData();
                    }
                    else {
                        alert(result.errorDesc);
                    }
                }
                else {
                    $("#loading").html('');
                }
            },
            error: function (result) {
                alert('Something error occured, please refresh the page.')
            }
        });
    };
  var CFChange = function ()
        {
            GetCFData();
        };

        var GetCFData = function ()
        {
            var TicketNumber = $('#txtHiddenTicketNumber').val();
            var RefundCode = $("#ddl-refund option:selected").val();

            $.ajax({
                url: '@Url.Action("GetCFData")',
                type: 'POST',
                data: { ticketNumber: TicketNumber, refundCode: RefundCode },
                success: function (result) {
                    console.log(result);
                    if (result.success) {
                        SetCFDetail(result.value);                  
                    }
                    else {
                    }
                },
                error: function (result) {
                    alert('Something error occured, please refresh the page.')
                }
            });
        };

var SetForm = function(list){
    $(list).each(function () {
        $('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
        $('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
        $('#lblPnrCode').html(this.PNR_CODE);
        $('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
        $('#lblIssuedDate').html(this.ISSUED_DATE_STR);
        $('#lblPassengerName').html(this.PASSENGER_NAME);
        $('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
        $('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
        $('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
        $('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
        $('#lblPublish').html(this.PUBLISH_RATE_STR);
        $('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
        $('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
        $('#lblAdminFee').html(this.ADMIN_FEE_STR);
        $('#lblCommFee').html(this.COMMISSION_FEE_STR);
        $('#lblTicketUsed').html(this.TICKET_USED);
        $('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
        $('#txtReason').val('');
        $('#ddl-refund :selected').text(this.CANCELLATION_FEE_PERCENTAGE_STR);
    });
};


var SetFormDetail = function (list) {
            $(list).each(function () {
                $('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
                $('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
                $('#lblPnrCode').html(this.PNR_CODE);
                $('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
                $('#lblIssuedDate').html(this.ISSUED_DATE_STR);
                $('#lblPassengerName').html(this.PASSENGER_NAME);
                $('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
                $('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
                $('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
                $('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
                $('#lblPublish').html(this.PUBLISH_RATE_STR);
                $('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
                $('#lblAdminFee').html(this.ADMIN_FEE_STR);
                $('#lblCommFee').html(this.COMMISSION_FEE_STR);
                $('#lblTicketUsed').html(this.USED_FEE_STR);
                $('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
                $('#txtReason').val(this.DESCRIPTION);
                $('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
                //$('#txtHiddenTicketNumber').val(this.TICKET_NUMBER);
                $("#ddl-refund").val(this.REFUND_CODE);
            });

            //GetCFData();
        };

        var SetFormView = function (list) {
            $(list).each(function () {
                $('#txtManualRefundNo').val(this.MANUAL_REFUND_NO);
                $('#lblLocOfficeCode').html(this.LOCATION_OFFICE_CODE);
                $('#lblPnrCode').html(this.PNR_CODE);
                $('#lblPnrTicket').html(this.PNR_CODE + "/ " + this.TICKET_NUMBER);
                $('#lblIssuedDate').html(this.ISSUED_DATE_STR);
                $('#lblPassengerName').html(this.PASSENGER_NAME);
                $('#lblRouteClass').html(this.ROUTE + "/ " + this.CLASS_CODE);
                $('#lblFlight').html(this.FLIGHT_DATE_STR + " - " + this.FLIGHT_NUMBER);
                $('#lblBaseComm').html(this.BASE_PRICE_STR + "/ " + this.COMMISSION_NOMINAL_STR);
                $('#lblTax').html(this.TOT_TAX_STR + "/ " + this.TOT_NON_TAX_STR);
                $('#lblPublish').html(this.PUBLISH_RATE_STR);
                $('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
                $('#lblAdminFee').html(this.ADMIN_FEE_STR);
                $('#lblCommFee').html(this.COMMISSION_FEE_STR);
                $('#lblTicketUsed').html(this.USED_FEE_STR);
                $('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
                $('#lblPaymentType').html(this.PAYMENT_TYPE);
                $('#lblReason').html(this.DESCRIPTION);
                $('#lblRefundPercentage').html(this.CANCELLATION_FEE_PERCENTAGE_STR);
                //$('#txtHiddenTicketNumber').val(this.TICKET_NUMBER);
                $("#ddl-refund").val(this.REFUND_CODE);
            });

            //GetCFData();
        };

        var SetCFDetail = function (list) {
            $(list).each(function () {
                $('#lblCancelFee').html(this.CANCELLATION_FEE_AMOUNT_STR);
                $('#lblAdminFee').html(this.ADMIN_FEE_STR);
                $('#lblCommFee').html(this.COMMISSION_FEE_STR);
                $('#lblTotalRefund').html(this.REFUND_AMOUNT_STR);
            });
        };

运行此操作后,视图始终不会根据与ticketnumber相关的sp选择百分比。我试图修改它但没有任何作用。很高兴能得到帮助:)。

1 个答案:

答案 0 :(得分:0)

这一行,

$('#ddl-refund :selected').text(this.CANCELLATION_FEE_PERCENTAGE_STR)

它实际上将当前所选选项的文本设置为this.CANCELLATION_FEE_PERCENTAGE_STR中的任何值。它实际上不会改变所选的选项。您可以在行动here中看到它。

您应该做什么从您的服务器调用中获取RefundCode值,并将其传递到val()方法中,以将特定选项设置为所选项目。

假设您的剃刀使用此标记呈现您的下拉列表。

<SELECT id="ddl-refund">
  <option value="25">Twenty Five</option>
  <option value="26">Twenty Six</option>
  <option value="28">Twenty Eight</option>
  <option value="29">Twenty Nine</option>

您从服务器调用收到的json数据有一个名为RedundCode的属性。

$(list).each(function () {
   $("#ddl-refund").val(this.RefundCode);
}

如果this.RefundCode为25或26或28或29,它将起作用。

我不太确定,当您要发送的所有内容都是单个项目时,为什么要发送数组。但这是另一回事。