How to add id to @Html.DisplayFor parameter?

人走茶凉 提交于 2021-02-05 10:44:06

问题


I looking for decision how to add a id to @Html.DisplayFor, that to this id I could tied jQuery method.

<dd>
    @Html.DisplayFor(model => model.Price)
</dd>

Thanks for some advise.


回答1:


The DisplayFor helper method simply renders the value of the expression you are passing to it. So in your case, let's say your Price property value is 235.34, The markup rendered by razor will be

<dd>
  235.34
</dd>

If all you care about reading the value of the Price property, you may consider keeping the value inside a hidden form element. You can use the HiddenFor helper method.

<dd>
    @Html.DisplayFor(model => model.Price)
    @Html.HiddenFor(a=>a.Price)
</dd>

This will render the below markup

<dd id="item">
    235.34
<input id="Price" name="Price" type="hidden" value="235.34" />
</dd>

You can see that now you have an input element with id Price. That means you can read the value in jQuery like

var v = $("#Price").val();

Another option is keeping the value in HTML5 data attributes.

<dd id="price" data-price="@Model.Price">
     @Html.DisplayFor(model => model.Price)
</dd>

and you can read it like

var v = $("#price").data("price");


来源:https://stackoverflow.com/questions/47381816/how-to-add-id-to-html-displayfor-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!