如何在Asp.Net MVC中为HiddenFieldFor设置默认值

时间:2010-08-17 12:45:20

标签: asp.net-mvc-2 html.hiddenfor

我正在使用HiddenFor和模型绑定,它是绑定值。 我想将绑定值重置为零。我该怎么做?

我试过这个,但它没有用......

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

2 个答案:

答案 0 :(得分:10)

您可以为此创建自己的帮助程序扩展名:

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

答案 1 :(得分:2)

只需将控制器操作中模型的ID属性设置为0