IDI am using the following code to create a drop down list:
@for (var index = 0; index < Model.AdminSummaries.Count(); index++)
{
&
My solution to this issue is to replace the id and name after DropDownListFor() with a html helper extension method.
public static MvcHtmlString ReplaceIdAndName(this MvcHtmlString htmlSource, string name)
{
MvcHtmlString result;
if (name == null)
result = htmlSource;
else
{
string id = name.Replace("[", "_").Replace("]", "_").Replace(".", "_"); // HTML ids cannot have []. so MVC convention replaces with _
XDocument html = XDocument.Parse(htmlSource.ToHtmlString());
html.Elements().Select(e => e.Attribute("id")).FirstOrDefault().SetValue(id);
html.Elements().Select(e => e.Attribute("name")).FirstOrDefault().SetValue(name);
result = MvcHtmlString.Create(html.ToString());
}
return result;
}
DropDownListFor(...).ReplaceIdAndName("myclass[1].myprop");
For those wondering why this doesn't work, the whole thing is case sensitive and need an @ in front of it...
so, this works:
new { @id = "myID", @Name = "myName", @Value = "myValue", @class = "form-control", @onchange = "javascript:DoSomething(this.value);" }
And this doesn't (mind the lowercase 'n' in @name
)
new { @id = "myID", @name = "myName", @Value = "myValue", @class = "form-control", @onchange = "javascript:DoSomething(this.value);" }
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" });
Just use "Name" instead of "name" and it works.
@Html.DropDownList("ClassID", null, "Select Class", htmlAttributes: new { id = _id, Name =_id, @class = "form-control" })
ID can be changed as described by @Arbiter. However, if you want to change the name, then I think you need to use @Html.DropDownList
rather than @Html.DropDownListFor
. This loses you any benefits of having the strong typing for the property element, but as just changing IDs means you can't access the values in a meaningful way if looking at the Request.Form
response, this may be an acceptable workaround for you.
You need to change From DropDownListFor To DropDownList. Than you can change name easily.
@Html.DropDownList("YourName", SelectList, new { @id = "YourId", @class = "YourClass" })
Hope It will work.