asp.net-mvc 如何使用 Html.EditorFor 和 MVC3 设置 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9189006/
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-08 01:43:18  来源:igfitidea点击:

How can I set id using Html.EditorFor with MVC3

asp.net-mvcasp.net-mvc-3

提问by Samantha J T Star

I am trying to set a field id as follows:

我正在尝试按如下方式设置字段 ID:

@Html.EditorFor(x => x.Order, new { id = string.Format("Order_{0}", Model.Row) })

but this results in the following and it seems my id is not being set:

但这会导致以下结果,似乎我的 ID 没有被设置:

<input type="text" value="334" name="item.Order" id="item_Order" class="text-box single-line">

Does anyone have an idea what I am doing wrong. I checked the allowable formats for EditorFor and looked on google for examples but I could not see anything that matched what I need.

有谁知道我做错了什么。我检查了 EditorFor 允许的格式并在谷歌上查找示例,但我看不到任何符合我需要的内容。

回答by dohaivu

You should change to

你应该改为

@Html.TextBoxFor(x => x.Order, new { id = string.Format("Order_{0}", Model.Row) })

The second parameter of @Html.EditorForis for view data, not for html attributes

的第二个参数@Html.EditorFor是针对视图数据的,不是针对html属性的

回答by Svetoslav Petrov

@Html.EditorFor(x => x.Order, null, string.Format("Order_{0}", Model.Row))

回答by Trevor Nestman

I know this question is pretty old, but all I needed to do was the following:

我知道这个问题已经很老了,但我需要做的就是以下几点:

@Html.EditorFor(modelItem => item.EndDate, 
                new { htmlAttributes = new { @class = "form-control", @id = @endID } })

You can give it whatever classes or id that you want/need. I have this earlier in my page as well to create a different ID for each item:

你可以给它任何你想要/需要的类或 id。我之前在我的页面中也有这个,为每个项目创建一个不同的 ID:

string endID = "end-" + @item.ID;

Hopefully this helps someone in the future.

希望这对将来的人有所帮助。

回答by AceMark

have you tried creating an editor template for your x.Order?

您是否尝试过为您创建编辑器模板x.Order

have this on your editor template:

在你的编辑器模板上有这个:

<input type="text" id="@ViewData["id"]">

and use this on your view page:

并在您的视图页面上使用它:

@Html.EditorFor(x => x.Order, new { id = string.Format("Order_{0}", Model.Row) })

回答by Tony Basallo

I'm not sure if you can override the ID attribute when using the strongly typed helpers. But you can use the other non-model type:

我不确定在使用强类型助手时是否可以覆盖 ID 属性。但是您可以使用其他非模型类型:

@Html.Editor(string.Format("Order_{0}", Model.Row), Model.Order)

This will use the first parameter as the ID and the second as the default value.

这将使用第一个参数作为 ID,第二个作为默认值。