在 asp.net mvc 2.0 中使用 Html.DropDownListFor helper 时如何更改 id 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2842342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:18:25  来源:igfitidea点击:

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

.netasp.net-mvcjquery-uiasp.net-mvc-2

提问by chobo2

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.

现在您可以创建新产品并编辑现有产品。编辑和创建都使用相同的表单。加载时创建在主页上。Edit 在 jQuery UI 模型对话框中弹出并呈现一个新的局部视图。

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"?

因此,就页面而言,我有 2 个具有相同“id”的下拉框,这很糟糕,因为它们应该是唯一的。那么怎么改id呢?因此,当编辑加载时,它的 ID 可能是“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

但它似乎并不关心并继续使用“SelectedProductName”作为产品名称

回答by Dave Swersky

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.)

我目前找不到文档,但是 DropDownListFor 有一个重载,它将接受对象类型的属性集合(HtmlAttributes 是参数名称。)

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.

您可以使用 Intellisense 查找包含 HtmlAttributes 的重载。

回答by Fernando Teles

You can use a hardcoded jQuery:

您可以使用硬编码的 jQuery:

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