Note that there are some explanatory texts on larger screens.

plurals
  1. POC# mvc 3 using selectlist with selected value in view
    primarykey
    data
    text
    <p>I'm working on a MVC3 web application. I want a list of categories shown when editing a blo from whe applications managements system. In my viewmodel i've got the following property defined for a list of selectlistitems for categories.</p> <pre><code>/// &lt;summary&gt; /// The List of categories /// &lt;/summary&gt; [Display(Name = "Categorie")] public IEnumerable&lt;SelectListItem&gt; Categories { get; set; } </code></pre> <p>The next step, my controller contains the following edit action where the list of selectlistitems is filled from the database.</p> <pre><code>public ActionResult Edit(Guid id) { var blogToEdit = _blogService.First(x =&gt; x.Id.Equals(id)); var listOfCategories = _categorieService.GetAll(); var selectList = listOfCategories.Select(x =&gt;new SelectListItem{Text = x.Name, Value = x.Id.ToString(), Selected = x.Id.Equals(blogToEdit.Category.Id)}).ToList(); selectList.Insert(0, new SelectListItem{Text = Messages.SelectAnItem, Value = Messages.SelectAnItem}); var viewModel = new BlogModel { BlogId = blogToEdit.Id, Active = blogToEdit.Actief, Content = blogToEdit.Text, Title = blogToEdit.Titel, Categories = selectList //at this point i see the expected item being selected //Categories = new IEnumerable&lt;SelectListItem&gt;(listOfCategories, "Id", "Naam", blogToEdit.CategorieId) }; return View(viewModel); } </code></pre> <p>When i set a breakpoint just before the view is being returned, i see that the selectlist is filled as i expected. So at this point everything seems to be okay. The viewmodel is filled entirely correct. Then in my view (i'm using Razor) i've got the following two rules which are supposed to render the selectlist for me.</p> <pre><code>@Html.LabelFor(m =&gt; m.Categories) @Html.DropDownListFor(model=&gt;model.Categories, Model.Categories, Model.CategoryId) @Html.ValidationMessageFor(m =&gt; m.Categories) </code></pre> <p>When I run the code and open the view to edit my blog, I can see all the correct data. Also the selectlist is rendered correctly, but the item i want to be selected lost it's selection. How can this be? Until the point the viewmodel is being returned with the view everything is okay. But when i view the webpage in the browser, the selectlist is there only with out the correct selection. What am I missing here? Or doing wrong?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload