SelectListItem selected = true not working in view

前端 未结 6 2045
醉酒成梦
醉酒成梦 2021-02-07 09:36

I have a gender select field (--Select--, Male, Female) and I\'m populating that in my controller. When the page loads, I want the gender that is selected in the model pm.

6条回答
  •  不思量自难忘°
    2021-02-07 10:20

    This is a known bug in ASP.NET MVC Razor View. As per the known bug documentation

    "The reason behind this problem is that asp.net MVC first looks for a match between the name of the drop down and property on the model. If there’s a match, the selected value of the SelectList is overridden. Changing the name of the drop down is all it takes to remedy the issue."

    I'm here giving a small example which you can use to test the resolution.

     var paymentTypeList = new List
                    {
                        new SelectListItem { Text = "Select Payment Type", Value = "NA" },
                        new SelectListItem { Text = "Card", Value = "Card" },
                        new SelectListItem { Text = "Paytm Wallet", Value = "Paytm Wallet" },
                        new SelectListItem { Text = "Cash", Value = "Cash", Selected = true },
                        new SelectListItem { Text = "Credit", Value = "Credit" },
                        new SelectListItem { Text = "Other", Value = "Other" }
                    };
     ViewBag.paymentTypeList = paymentTypeList;
    

    Resolution Option 1 (Easiest) - Change the Name of declaration id of select list id in MVC view e.g

    @Html.DropDownList("paymentTypeListNew", (List)ViewBag.paymentTypeList, new { @class = "form-control select2 select1" })
    

    Resolution 2: (Use only single constructor of @Html.DropDownList that matches viewbag/viewdata property)

    To ensure that selected item (cash in this example) gets selected do the following in MVC Razor View. Use only the following constructor without any CSS or new object values

     @Html.DropDownList("paymentTypeList") 
    

    Now if you are worried that you cannot initialize the CSS then you need to initialize the css programitally. For example if you are using Jquery then can you can use

    $("#paymentTypeList").addClass("form-control");
                $("#paymentTypeList").addClass("select2");
    

提交回复
热议问题