Perfect, now the value is selected in the list as expected. BUT, the problem with this however is that is the DropDownList no longer binds to the model as needed. Since we've changed the name, updates to the database do not work. After reading numerous posts on Stackoverflow I discovered zero solutions.
Here is how I resolved it:
Assuming that your SelectList is constructed in your Controller or ViewModel like this:
CatsRepository CatsRepo = new CatsRepository();
CatsList = new SelectList(CatsRepo.FindCats(), "CatId", "Category", Content.CatId);
The HTML.DropDownList can be constructed in your control like this:
%lt;input type="hidden" name="CatId" id="CatId" value="" /%gt;
%lt;%= Html.DropDownList("CatIdList", Model.CatsList, new { @onchange = "CatId.value = this.value"})%%gt;
In Summary,
1) I renamed my "CatId" bound DropDownList to "CatIdList".
2) Then I added a hiddel field named "CatId" setting it's value to "".
3) I added a "new { @onchange = "CatId.value = this.value"}" as an htmlAttribute to my DropDownList, so when a different value is picked it updates the hidden field value accordingly.
No comments:
Post a Comment