Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC - Html.DropDownList - Value not set via ViewData.Model
    primarykey
    data
    text
    <p>Have just started playing with ASP.NET MVC and have stumbled over the following situation. It feels a lot like a bug but if its not, an explanation would be appreciated :)</p> <p>The View contains pretty basic stuff</p> <pre><code>&lt;%=Html.DropDownList("MyList", ViewData["MyListItems"] as SelectList)%&gt; &lt;%=Html.TextBox("MyTextBox")%&gt; </code></pre> <p>When not using a model, the value and selected item are set as expected:</p> <pre><code>//works fine public ActionResult MyAction(){ ViewData["MyListItems"] = new SelectList(items, "Value", "Text"); //items is an ienumerable of {Value="XXX", Text="YYY"} ViewData["MyList"] = "XXX"; //set the selected item to be the one with value 'XXX' ViewData["MyTextBox"] = "ABC"; //sets textbox value to 'ABC' return View(); } </code></pre> <p>But when trying to load via a model, the textbox has the value set as expected, but the dropdown doesnt get a selected item set.</p> <pre><code>//doesnt work public ActionResult MyAction(){ ViewData["MyListItems"] = new SelectList(items, "Value", "Text"); //items is an ienumerable of {Value="XXX", Text="YYY"} var model = new { MyList = "XXX", //set the selected item to be the one with value 'XXX' MyTextBox = "ABC" //sets textbox value to 'ABC' } return View(model); } </code></pre> <p>Any ideas? My current thoughts on it are that perhaps when using a model, we're restricted to setting the selected item on the SelectList constructor instead of using the viewdata (which works fine) and passing the selectlist in with the model - which would have the benefit of cleaning the code up a little - I'm just wondering why this method doesnt work....</p> <p>Many thanks for any suggestions</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.
 

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