Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dropdownlist set selected value in MVC3 Razor

Here is my model:

public class NewsCategoriesModel {     public int NewsCategoriesID { get; set; }             public string NewsCategoriesName { get; set; } } 

My controller:

public ActionResult NewsEdit(int ID, dms_New dsn) {     dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();     var categories = (from b in dc.dms_NewsCategories select b).ToList();     var selectedValue = dsn.NewsCategoriesID;     SelectList ListCategories = new SelectList(categories, "NewsCategoriesID", "NewsCategoriesName",selectedValue);      // ViewBag.NewsCategoriesID = new SelectList(categories as IEnumerable<dms_NewsCategory>, "NewsCategoriesID", "NewsCategoriesName", dsn.NewsCategoriesID);     ViewBag.NewsCategoriesID = ListCategories;     return View(dsn); } 

And then my view:

@Html.DropDownList("NewsCategoriesID", (SelectList)ViewBag.NewsCategoriesID) 

When i run, the DropDownList does not select the value I set.. It is always selecting the first option.

like image 842
Raito Light Avatar asked Jul 24 '11 14:07

Raito Light


People also ask

How can set the selected value of dropdown in asp net?

You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error. dropdownlist. ClearSelection(); dropdownlist.


1 Answers

You should use view models and forget about ViewBag Think of it as if it didn't exist. You will see how easier things will become. So define a view model:

public class MyViewModel {     public int SelectedCategoryId { get; set; }     public IEnumerable<SelectListItem> Categories { get; set; }  } 

and then populate this view model from the controller:

public ActionResult NewsEdit(int ID, dms_New dsn) {     var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();     var categories = (from b in dc.dms_NewsCategories select b).ToList();      var model = new MyViewModel     {         SelectedCategoryId = dsn.NewsCategoriesID,         Categories = categories.Select(x => new SelectListItem         {             Value = x.NewsCategoriesID.ToString(),             Text = x.NewsCategoriesName         })     };     return View(model); } 

and finally in your view use the strongly typed DropDownListFor helper:

@model MyViewModel  @Html.DropDownListFor(     x => x.SelectedCategoryId,     Model.Categories ) 
like image 88
Darin Dimitrov Avatar answered Oct 09 '22 02:10

Darin Dimitrov