Question

I Have 2 views. ProductForm.aspx and Category.ascx. CategoryForm is a Partial View. I Call the Category.ascx from the ProductForm with EditorFor(model => model.Category) . In this partial view, there is a DropdownlistFor with all the category. The problem is the Selected Value for a specific Product Category. The selected value dosen't work.

Why ?


Here is what I have in my ProductForm

<div class="editor">      
    <div class="editor-label">
        <%: Html.LabelFor(model => model.ProductInfo.ProductName) %>
    </div>

    <div class="editor-field">
        <%: Html.TextBoxFor(model => model.ProductInfo.ProductName)%>
        <%: Html.ValidationMessageFor(model => model.ProductInfo.ProductName)%>
    </div>
</div>
<%: Html.EditorFor(model => model.ProductInfo.Category, new { CategoryList = Model.CategoryList })%>


In Category.ascx

<div class="editor-field">
   <%:Html.DropDownListFor(model => model.CategoryID, (IEnumerable<SelectListItem>)ViewData["CategoryList"])%>
</div>
Was it helpful?

Solution

You can assign the name attribute of your DDL to whatever your CategoryID/foreign key is called in your Products table. Then your DDL will automatically select that category, due to how default binding works.

One example:

<%: Html.DropDownList("Book.GenreID" , Model.GenresSelectList )%>

and the resulting html:

<select id="Book_GenreID" name="Book.GenreID">
<option value="2">Horror</option>
<option selected="selected" value="3">Literature</option>
<option value="1">Science Fiction</option>
</select>

or:

<%: Html.DropDownListFor(model => model.Book.GenreID, Model.GenresSelectList )%>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top