Edit does not work with Html.DropDownList and @class attributes

Controller:

ViewBag.Category = new SelectList(this.service.GetAllCategories(), product.Category); 

I do not use Id + Name. GetAllCategories () returns only a few int numbers.

When I use in a view:

 @Html.DropDownList("Category", String.Empty) 

everything works. Editing is normal, and DropDownList shows the selected value. HTML Result:

 <select id="Category" name="Category"> <option value=""></option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option selected="selected">5</option> ... </select> 

But I need to use css @class, so I use this code:

 @Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" }) 

HTML Result:

 <select class="anything" id="Category" name="Category"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> ... </select> 

Unfortunately, Edit still works (I can save the value that I select), but DropDownList starts showing the default value, not the value stored in the database .

Do you have any ideas what the problem is?

Update I clarified what to clarify.

The GetAllCategories method is as follows:

 public List<int> GetAllCategories() { List<int> categories = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; return categories; } 
+4
source share
3 answers

Html.DropDownList works pretty interesting:
If you do not provide a pick list

 @Html.DropDownList("Category", String.Empty) 

it will look for values ​​to select from ViewData/ViewBag based on the provided property name: Category .
But if you provide a selection list, it will look for the default item in the ViewData/ViewBag based on the supplied Category property name, which, of course, will contain the list instead of the default value. To fix this, you have two options:

Do not specify a selection list:

@Html.DropDownList("Category", null, new { @class = "anything" })

Or
Use a different name instead of the name of the ViewBag Category property:

@Html.DropDownList("CategoryDD", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })

+6
source
  SelectList typelist = new SelectList(this.service.GetAllCategories(), "ProductID", "ProductName", product.Category); ViewBag.Category=typelist; 

I think that from your table you should get the default values ​​"ProductID" and the text "ProductName" or the one you use and want to display so that a list can be generated for these results.

Not sure what your problem is, but you can try it, maybe it will solve it.

0
source

You can use the dropdown list for the html helper. Note that the view requires the β€œmodel” that you expect.

 @Html.DropDownListFor(model => model.savedID, (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" }) 
0
source

Source: https://habr.com/ru/post/1380820/


All Articles