mvc html.hidden,ASP.Net MVC Html.HiddenFor有错误的值

此代码无效

// 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;

...因为HiddenFor always(!)从ModelState读取而不是模型本身 . 如果它没有找到“Step”键,它将产生该变量类型的默认值,在这种情况下它将为0

这是解决方案 . 我是为自己写的,但不介意分享它,因为我看到很多人都在为这个顽皮的HiddenFor帮手挣扎 .

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)

};

}

}

}

然后你可以像往常一样在你看来使用它:

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

值得一提的是它也适用于收藏品 .

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值