我已经阅读了该问题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,变量结果包含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);
            });
        };


运行此命令后,视图始终不会基于与票证编号相关的sp选择百分比。我试图对其进行修改,但没有任何效果。乐于助人:)

最佳答案

这条线

$('#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,它将起作用。

我不太确定,为什么要发送的数组只有一个项目,为什么还要发送数组。但这是另一回事要解决。

07-25 20:52