gpt4 book ai didi

jquery - MVC3 Html.DisplayFor -- 是否可以让该控件生成 ID?

转载 作者:行者123 更新时间:2023-12-03 22:23:33 25 4
gpt4 key购买 nike

我希望能够显示一些文本,而且还可以通过 jQuery 修改文本。

<%= Html.DisplayFor(model => model.DeviceComponentName)%>

如果我使用 EditorFor 而不是 DisplayFor,我会看到输入控件的 ID。不过,我不希望该值以这种方式可编辑。因此,我将其设为 DisplayFor,但它不会为该元素生成 ID 属性。

我应该将 DisplayFor 包装在 div 中并执行以下操作:

<div id="<%= ViewData.TemplateInfo.GetFullHtmlFieldName("DeviceComponentName") %>">
<%= Html.DisplayFor(model => model.DeviceComponentName)%>
</div>

$('#DeviceComponentName').text('newValue');

或者有没有更简洁的方法来实现这一目标?

更新:有没有一种不依赖于硬编码字符串的方法?与对象本身相关的东西,因此如果我的属性名称发生更改,我会收到编译错误?

此外,我正在使用此代码,但我没有看到 ID 值出现:

<td class="editableValue">
<%--Label should be editable, so it needs an ID, but only will be edited by jQuery so it can't be an EditorFor--%>
<%= Html.DisplayFor(model => model.DeviceComponentName, new { id = "DeviceComponentName" })%>
<button type="button" id="ComponentTreeButton" class="nestedDialogButton">...</button>
</td>

最佳答案

为了避免“魔术字符串”输入(如果模型属性发生变化),您可以使用扩展来执行此操作。它还使代码更加简洁:

public static MvcHtmlString DisplayWithIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string wrapperTag = "div")
{
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}</{0}>", wrapperTag, id, helper.DisplayFor(expression)));
}

然后像这样使用它:

@Html.DisplayWithIdFor(x => x.Name)

将产生

<div id="Name">Bill</div>

或者,如果您希望将其包裹在跨度中:

@Html.DisplayWithIdFor(x => x.Name, "span")

这将使得:

<span id="Name">Bill</span>

非 Razor

对于非 Razor 语法,您只需像这样使用它:

<%= Html.DisplayWithIdFor(x => x.Name) %>

和:

<%= Html.DisplayWithIdFor(x => x.Name, "span") %>

关于jquery - MVC3 Html.DisplayFor -- 是否可以让该控件生成 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com