I have a couple of properties in my view model that are display-only but I need to retrieve their values using jQuery to perform a calculation on the page. The standard Html.DisplayFor() method just writes their value to the page. I want to create a razor template that will allow me to render each element as:
<span id="ElementsId">Element's value</span>
I know I can specify a template in Html.DisplayFor() to use a particular template for rendering the property but within that template how do I identify the id attribute to write into the span tag?
@Html.DisplayFor(model => model.Element, "MyTemplate");
DisplayFor() The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.
Razor is a templating engine that was introduced with ASP.NET MVC, originally to run on the server and generate HTML to be served to web browsers. The Razor templating engine extends standard HTML syntax with C# so that you can express the layout and incorporate CSS stylesheets and JavaScript easily.
Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
A Razor Page is almost the same as ASP.NET MVC's view component. It has basically the syntax and functionality same as MVC. The basic difference between Razor pages and MVC is that the model and controller code is also added within the Razor Page itself. You do not need to add code separately.
OK, I found it and it's actually very simple. In my Views\Shared\DisplayTemplates folder I have Reading.cshtml containing the following:
@model System.Int32 <span id="@ViewData.ModelMetadata.PropertyName">@Model</span>
This renders the correct tag using the name of the property as the id attribute and the value of the property as the contents:
<span id="Reading">1234</span>
In the view file this can be called using the following:
@Html.DisplayFor(model => model.Reading, "Reading")
Or if the model property is decorated with UIHint("Reading") then the template name can be left out of the call to DisplayFor() and it will still render using the template:
@Html.DisplayFor(model => model.Reading)
This should work equally well with custom editor templates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With