Html.Hidden领域没有得到设置 [英] Html.Hidden field not getting set

查看:122
本文介绍了Html.Hidden领域没有得到设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个隐藏字段在我看来是这样的:

 使用(Html.BeginForm(动作,时间表))
{
    @ Html.Hidden(ID,Model.Schedule.Id)
    ...
}

而这需要在这样的信息的操作方法:

 公众的ActionResult AddEventToSchedule(事件NewEvent,而是的Guid标识)
{
    // 做一点事
}

我不断收到一个空的Guid传入,即使Model.Schedule.Id不是空的。我检查了html源代码和隐藏字段为空的Guid和(使用断点来验证Model.Schedule.Id不为空)。

但奇怪的是,当我试图通过像下面的模型来访问的ID值,在HTML隐藏字段正确的GUID填充,但传递到操作方法的型号是空的。

 公众的ActionResult AddEventToSchedule(事件NewEvent,而是ScheduleModel模型)
{
    // model.Schedule为空!
}


解决方案

这出这个问题的帮助:
MVC3模型绑定 - 列表以隐藏字段

显然HTML辅助检查ModelState中的价值,他们检查模型前。
当我加入了ID作为参数来操作方法,为什么我只看到了这种现象的原因是,这个调用模型绑定的标识来填充的ModelState。以及为什么该ID的原因总是空的Guid是因为这是值的第一次动作方法被调用。

我添加这一行到我的操作方法和现在一切都正常工作:

  ModelState.Remove(ID)

I have a hidden field in my view like this:

using (Html.BeginForm("Action", "Schedule"))
{
    @Html.Hidden("Id", Model.Schedule.Id)
    ...
}

And an action method that takes in the information like this:

public ActionResult AddEventToSchedule(Event NewEvent, Guid Id)
{
    // Do something
}

I keep getting an empty Guid passed in, even when Model.Schedule.Id is not empty. I checked the html source and the hidden field is an empty Guid as well (used a breakpoint to verify that Model.Schedule.Id is not empty).

The strange thing is when I tried to access the Id value through the model like below, the html hidden field was populated correctly with the guid, but the model passed into the action method was empty.

public ActionResult AddEventToSchedule(Event NewEvent, ScheduleModel model)
{
    // model.Schedule is null!
}

解决方案

Figured this out with the help of this question: MVC3 Model Binding - List to Hidden fields

Apparently HTML helpers check ModelState for a value before they check Model. The reason why I only saw this behavior when I added the Id as a parameter to the action method was that this invoked the model binder to populate ModelState with the Id. And the reason why the Id was always an empty Guid was because that's the value the first time the action method is called.

I added this line to my action method and everything works fine now:

ModelState.Remove("Id")

这篇关于Html.Hidden领域没有得到设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆