How can i set Default value for HiddenFieldFor In Asp.Net MVC

旧巷老猫 提交于 2019-12-10 16:28:45

问题


i am using HiddenFor with model binding which is binding value to it. i want to reset the binded value to zero.How can i do it?

i tried this but it is not working...

<% foreach (var item in Model ) { %>
 <%: Html.HiddenFor(model => model.ID,new { @value="0"})%>
 <% } %>

回答1:


You can create your own helper extension for that:

public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
    var propertyName = ExpressionHelper.GetExpressionText(expression);

    var input = new TagBuilder("input");
    input.MergeAttribute("id", helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldId(propertyName)));
    input.MergeAttribute("name", helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName)));
    input.MergeAttribute("value", value.ToString());
    input.MergeAttribute("type", "hidden");
    input.MergeAttributes(new RouteValueDictionary(htmlAttributes));

    return MvcHtmlString.Create(input.ToString());
}



回答2:


Simply set the ID property of your model in the controller action to 0.



来源:https://stackoverflow.com/questions/3502498/how-can-i-set-default-value-for-hiddenfieldfor-in-asp-net-mvc

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