How to add id to @Html.DisplayFor parameter?

前端 未结 1 951
一整个雨季
一整个雨季 2021-01-28 20:57

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

@Html.DisplayFor(model => model.Price)
相关标签:
1条回答
  • 2021-01-28 21:05

    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");
    
    0 讨论(0)
提交回复
热议问题