How to add id to @Html.DisplayFor parameter?

前端 未结 1 982
一整个雨季
一整个雨季 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

    235.34

    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.

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

    This will render the below markup

    235.34

    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.

    @Html.DisplayFor(model => model.Price)

    and you can read it like

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

    0 讨论(0)
提交回复
热议问题