mvc html.hidden,ASP.Net MVC Html.HiddenFor with wrong value

This code will not work

// remove the Step variable from the model state

// if you want the changes in the model to be

// taken into account

ModelState.Remove("Step");

model.Step = 2;

...because HiddenFor always (!) reads from ModelState not the model itself. And if it doesn't find the "Step" key it will produce the default for that variable type which will be 0 in this case

Here is the solution. I wrote it for myself but don't mind sharing it cause I see many people are struggling with this naughty HiddenFor helper.

public static class CustomExtensions

{

public static MvcHtmlString HiddenFor2(this HtmlHelper htmlHelper, Expression> expression)

{

ReplacePropertyState(htmlHelper, expression);

return htmlHelper.HiddenFor(expression);

}

public static MvcHtmlString HiddenFor2(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes)

{

ReplacePropertyState(htmlHelper, expression);

return htmlHelper.HiddenFor(expression, htmlAttributes);

}

public static MvcHtmlString HiddenFor2(this HtmlHelper htmlHelper, Expression> expression, IDictionary htmlAttributes)

{

ReplacePropertyState(htmlHelper, expression);

return htmlHelper.HiddenFor(expression, htmlAttributes);

}

private static void ReplacePropertyState(HtmlHelper htmlHelper, Expression> expression)

{

string text = ExpressionHelper.GetExpressionText(expression);

string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(text);

ModelStateDictionary modelState = htmlHelper.ViewContext.ViewData.ModelState;

ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

if (modelState.ContainsKey(fullName))

{

ValueProviderResult currentValue = modelState[fullName].Value;

modelState[fullName].Value = new ValueProviderResult(metadata.Model, Convert.ToString(metadata.Model), currentValue.Culture);

}

else

{

modelState[fullName] = new ModelState

{

Value = new ValueProviderResult(metadata.Model, Convert.ToString(metadata.Model), CultureInfo.CurrentUICulture)

};

}

}

}

Then you just use it as usual from within you view:

@Html.HiddenFor2(m => m.Id)

It worth to mention it works with collections too.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值