Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change the html name generated by Html.DropDownListFor?

IDI am using the following code to create a drop down list:

 @for (var index = 0; index < Model.AdminSummaries.Count(); index++)              {              <div class="rep_tr0">                  <div class="rep_td0">                      @Html.DropDownListFor(x => Model.AdminSummaries[index].Status, AdminStatusReference.GetAdminStatusOptions())                  </div>  

The code creates the following:

<select id="AdminSummaries_2__Status" name="AdminSummaries[2].Status">    <option value="1">Released</option>    <option value="2">Review</option>    <option value="3">New</option> </select>  <select id="AdminSummaries_3__Status" name="AdminSummaries[3].Status">    <option value="1">Released</option>    <option value="2">Review</option>    <option value="3">New</option> </select>  

Is there any way that I could change it so that it creates a ID of "Status_2", "Status_3" etc.

like image 882
Samantha J T Star Avatar asked Dec 29 '11 14:12

Samantha J T Star


People also ask

How can give ID to HTML DropDownList in MVC?

In order to set html attributes inside @Html. DropDownListFor , you have to set 4th parameter of @Html. DropDownListFor with new keyword which will create a object for htmlattributes .


2 Answers

Like @Anar said in the comments;

Actually, you can change the name attribute the same way as id, but instead of "name", use "Name". Surprisingly it works.

 @Html.DropDownListFor(x => Model.AdminSummaries[index].Status,  AdminStatusReference.GetAdminStatusOptions(),  new { id = string.Format("Status_{0}",index ), Name = "GiveName" }); 
like image 102
hmz Avatar answered Sep 29 '22 22:09

hmz


Sometimes the HTML helpers don't HELP. DropDownListFor coding can get complicated real fast and in the end it's just rendering HTML so sometimes it's better to go old school

<select name="myname" class="dropdownlist" id="myid">     @foreach (SelectListItem item in Model.SomeSelectList) {         if (item.Value ==  Model.theValue) {             <option value="@(item.Value)" selected="selected">@item.Text</option>         } else {             <option value="@(item.Value)">@item.Text</option>         }     } </select> 
like image 32
nuander Avatar answered Sep 29 '22 21:09

nuander