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?
Alternatively you can use this as well
The
DisplayFor
helper doesn't generate any HTML tags, it just outputs the formatted text. So you cannot addid
attribute to it. What you could do instead is to wrap it in a tag (div or span):and then be able to manipulate the contents of this tag:
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 yourid
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:
And then in your view, you can use it like this:
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:
And then in your view, you can use it like this:
That code is an adaption from David Clarke's answer here