最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add id to @Html.DisplayFor - Stack Overflow

programmeradmin2浏览0评论

I'm trying to add id to

@Html.DisplayFor(model => model.ScreenWidth, new { @id = "width"})

and then use

document.getElementById("width").innerHTML = w;

Why is it not working?

I'm trying to add id to

@Html.DisplayFor(model => model.ScreenWidth, new { @id = "width"})

and then use

document.getElementById("width").innerHTML = w;

Why is it not working?

Share Improve this question edited Jan 30, 2017 at 7:47 user3559349 asked Jan 30, 2017 at 7:25 ZetZet 5714 gold badges14 silver badges32 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 10

The DisplayFor helper doesn't generate any HTML tags, it just outputs the formatted text. So you cannot add id attribute to it. What you could do instead is to wrap it in a tag (div or span):

<div id="width">
    @Html.DisplayFor(model => model.ScreenWidth)
</div>

and then be able to manipulate the contents of this tag:

document.getElementById("width").innerHTML = w;

One other approach to this is to create a customised Display Template that you can then use to render both the value and, say, a <span> tag that contains your id attribute.

If you want your id set to something custom, rather than the name of the property:

Create a file called SpanWithId.cshtml in Views\Shared\DisplayTemplates (create any of those folders if they are missing) and add this code:

<span id="@(ViewBag.HtmlID)">@Model</span>

And then in your view, you can use it like this:

@Html.DisplayFor(model => model.ScreenWidth, "SpanWithId", new { HtmlID = "project-name" })

That code is an adaption from Phillip Smith's answer here

If you want your id and name set to the name of the property:

Create a file called SpanWithIdAndName.cshtml in Views\Shared\DisplayTemplates (create any of those folders if they are missing) and add this code:

@{var fieldName = ViewData.TemplateInfo.HtmlFieldPrefix;}
<span id="@fieldName" name="@fieldName">@Model</span>

And then in your view, you can use it like this:

@Html.DisplayFor(model => model.ScreenWidth, "SpanWithIdAndName")

That code is an adaption from David Clarke's answer here

Alternatively you can use this as well

      <span id="width">@Html.Displayfor(model => model.ScreenWidth) </span>

I am assuming that you are just wanting to display a label. This is how I acplished this.

<label id="lblName">
    @Html.Raw(@Model.ObjectA.ObjectB.ObjectC.ToString())
</label>

Then if I want to change the value in jQuery, I can:

$('#lblName').text("New Value");
发布评论

评论列表(0)

  1. 暂无评论