How to change id value when using Html.DropDownListFor helper in asp.net mvc 2.0?

不想你离开。 提交于 2019-12-21 07:01:14

问题


I have a partial view that has something like this

 <%= Html.DropDownListFor(m => m.SelectedProductName, Model.ProductList, "Select a Product") %>

Now you can create a new product and edit an existing product. Both editing and creating use the same form. The create is on the main page on load up. Edit pops up in a jQuery UI model dialog and renders a new partial view.

So as far as the page is concerned I have 2 dropdown boxes with the same "id" which is bad since they should be unique. So how do I change the id? So when the edit loads it might have a id of "editSelectedProductName"?

I tried to do this in the view model

public string SelectedProductName{ get; set; }

ViewModelConstructor()
{
  SelectedProductName = "EditSelectedProductName";
}

But it seems to not care and keeps using "SelectedProductName" as the product name


回答1:


I can't find the documentation at the moment, but there is an overload for DropDownListFor that will accept an object-typed collection of attributes (HtmlAttributes is the parameter name.)

It will look something like this:

Html.DropDownListFor(model=>model.SomeProperty, new {@id="UniqueID1234"});

You can use Intellisense to find the overload that includes HtmlAttributes.




回答2:


You can use a hardcoded jQuery:

$('select#[id of your select box]').attr('id', '[id that you want]');


来源:https://stackoverflow.com/questions/2842342/how-to-change-id-value-when-using-html-dropdownlistfor-helper-in-asp-net-mvc-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!