2

I have read through this question ASP.NET MVC DropDownListFor not selecting value from model and answer but I don't know the solution to my problem.

This is part of my controller, here is first time when I call the ddl for the view, but not yet select any value.

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);
}

Then here is the selected value is being selected from controller,

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);
        }

The selected value is about CfPercentage and variable result contains CF_PERCENTAGE which is representate of CfPercentage,

And here is my view and 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);
            });
        };

After I running this, the view is always not select percentage based on sp that is relevant to ticketnumber. I have tried to modified it but nothing works. feel happy to be help :)

Community
  • 1
  • 1

1 Answers1

0

This line,

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

It actually set's the currently selected option's text to whatever value in this.CANCELLATION_FEE_PERCENTAGE_STR . It won't actually change the selected option. You can see it in action here.

What you should be doing Get the RefundCode value from your server call, and pass that in the val() method to set specific option item as the selected item.

Assuming your razor rendered your dropdown with this markup.

<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>

And json data you received from your server call has a property called RedundCode.

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

It will work if this.RefundCode is either 25 or 26 or 28 or 29.

I am not quite sure, why you are sending an array when all you want to send is a single item. But that is a different thing to fix.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • thanks I'll try that, but I have problem that sp on controller doesn't have 'RefundCode' that's why I get it by percentage, maybe I will update my post with complete code so you can see where is actually the problem. I'm sending an array for other property not only ddl but I'm not post that other property like lblFlight and the others. – Febrian Nur Dec 28 '15 at 06:31