且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能设置HiddenFieldFor默认值在Asp.Net MVC

更新时间:2022-10-26 16:00:00

您可以创建自己的帮助扩展是:

 公共静态MvcHtmlString HiddenFor<的TModel,TProperty>(此的HtmlHelper<的TModel>的帮手,防爆pression< Func键<的TModel,TProperty>>前pression,对象值,对象htmlAttributes)
{
    VAR propertyName的防爆= pressionHelper.GetEx pressionText(如pression);    VAR输入=新TagBuilder(输入);
    input.MergeAttribute(ID,helper.AttributeEn code(helper.ViewData.TemplateInfo.GetFullHtmlFieldId(propertyName的)));
    input.MergeAttribute(名,helper.AttributeEn code(helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName的)));
    input.MergeAttribute(价值,value.ToString());
    input.MergeAttribute(类型,隐藏);
    input.MergeAttributes(新RouteValueDictionary(htmlAttributes));    返回MvcHtmlString.Create(input.ToString());
}

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"})%>
 <% } %>

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());
}