Dropdown list is not showing selected value

Joe Green 146 Reputation points
2022-06-27T11:17:13.25+00:00

In my .net MVC application, I have a model like this

    public class PCB  
    {  
        public Guid Id { get; set; }  
        public float A { get; set; }  
        public float B { get; set; }  
        public bool C { get; set; }  
        public string D  { get; set; }  
    }  

In my Edit view, as you can see D is a dropdownlist and it is clickable only if C is true

                @Html.Hidden("hdnOldD", Model.D)  
                @if (Model.C == true)  
                {  
                    @Html.DropDownListFor(model => model.D, (SelectList)ViewData["D"], "-- Please Select D --", new { @class = "form-control" })  
                }  
                else  
                {  
                    @Html.DropDownListFor(model => model.D, (SelectList)ViewData["D"], "-- Please Select D --", new { @class = "form-control", @style = "pointer-events: none" })  
                }  
                @Html.ValidationMessageFor(model => model.D, "", new { @class = "text-danger" })  

In my Edit controller, I have this to

            OCB test = db.OCB.Find(id);  
            string selectedD = test.D.ToString().Trim();  
            ViewData["D"] = new SelectList((from c in db.OCB  
                                             select new  
                                             {  
                                             value = c.A.ToString().Trim() + ":" + c.B.Trim() + ":" + c.C.ToString().Trim(),  
                                             text = c.A.ToString().Trim() + ":" + c.B.Trim() + ":" + c.C.ToString().Trim()  
                                             }).Distinct().OrderBy(c => c.text),  
                                             "value",  
                                             "text",  
                                             selectedD);  

As you can see value stored in D is combination of A, B and C in a format A:B:C

In my Edit view, I can see dropdownlist is correctly populated from the database, but it is not showing the selected value.

What am I missing here?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,248 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Joe Green 146 Reputation points
    2022-06-27T16:30:52.697+00:00

    It turns out my ViewData name D was same as property name D. Once I changed ViewData name, Dropdownlist showed the correct selected value.


  2. SurferOnWww 1,906 Reputation points
    2022-06-28T01:59:59.02+00:00

    I suggest that you use the scaffolding function of Visual Studio to generate the controller and views to perform the CRUD operations and to see the code for the Edit. Described below is an example:

    (1) Create the EDM from the Products, Categories and Suppliers tables of Northwind sample database:

    215542-northwindjpg-th.jpg

    (2) Perform the scaffolding to generate the controller and views for the CRUD operations for the Products table based on the above EDM.

    (3) Execute the application and show the Edit view. Confirm that Categories and Suppliers are shown in drop downs and the items are selected properly:

    215552-editjpg-th.jpg

    (4) See the codes of Edit action method and the Edit.cshtml.

    Edit action method

    public async Task<ActionResult> Edit(int? id)  
    {  
        if (id == null)  
        {  
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
        }  
        Products products = await db.Products.FindAsync(id);  
        if (products == null)  
        {  
            return HttpNotFound();  
        }  
        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", products.CategoryID);  
        ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", products.SupplierID);  
        return View(products);  
    }  
    

    Edit.cshtml (drop down portions only)

    <div class="form-group">  
        @Html.LabelFor(model => model.SupplierID, "SupplierID", htmlAttributes: new { @class = "control-label col-md-2" })  
        <div class="col-md-10">  
            @Html.DropDownList("SupplierID", null, htmlAttributes: new { @class = "form-control" })  
            @Html.ValidationMessageFor(model => model.SupplierID, "", new { @class = "text-danger" })  
        </div>  
    </div>  
      
    <div class="form-group">  
        @Html.LabelFor(model => model.CategoryID, "CategoryID", htmlAttributes: new { @class = "control-label col-md-2" })  
        <div class="col-md-10">  
            @Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" })  
            @Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })  
        </div>  
    </div>  
    

    (5) The DropDownList obtains the data given from ViewBag based on the name given in the 1st argument and selects the item according to the 4th argument of SelectList set in the Edit action method.

    Note that the 2nd augment of @azzedinehtmlsql .DropDownList must be null. This is important to make the DropDownList to select the item according to the 4th argument of SelectList in the Edit action item.

    0 comments No comments