Hiddenfor没有得到从视图模型正确的值 [英] Hiddenfor not getting correct value from view model

查看:149
本文介绍了Hiddenfor没有得到从视图模型正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多步骤的文件导入过程。我有我的观点,我想从视图模型的CurrentStep来填充一个隐藏的表单输入。

I have a multi-step file import process. I have a hidden form input in my view that I am trying to populate with the "CurrentStep" from the view model.

<% = Html.HiddenFor(model => model.CurrentStep) %>

CurrentStep是一个枚举,我总是得到默认值,而不是我的视图模型提供的之一。在另一方面,这让我正确的值:

CurrentStep is an Enum and I always get the default value rather than the one I provided to the view model. on the other hand this gets me the correct value:

<p><% = Model.CurrentStep %></p>

我知道我可以只手code隐藏的输入,但我想知道:我究竟做错了什么?有没有更好的方法来跟踪岗位之间当前步骤?

I realise I could just hand code the hidden input but I want to know: what am I doing wrong? Is there a better way to keep track of the current step between POSTs?

先谢谢了。

推荐答案

你在做什么错的是你要修改你的控制器动作贴出变量的值。所以我想你想做到这一点:

What you are doing wrong is that you are trying to modify the value of a POSTed variable in your controller action. So I suppose you are trying to do this:

[HttpPost]
public ActionResult Foo(SomeModel model)
{
    model.CurrentStep = Steps.SomeNewValue;
    return View(model);
}

和HTML助手,如HiddenFor总是会首先使用张贴的值,随后将在模型中的价值。

and html helpers such as HiddenFor will always first use the POSTed value and after that the value in the model.

所以,你有几个可能的原因:

So you have a couple of possibilities:


  1. 从ModelState中删除值:

  1. Remove the value from the modelstate:

[HttpPost]
public ActionResult Foo(SomeModel model)
{
    ModelState.Remove("CurrentStep");            
    model.CurrentStep = Steps.SomeNewValue;
    return View(model);
}


  • 手动生成隐藏字段

  • Manually generate the hidden field

    <input type="hidden" name="NextStep" value="<%= Model.CurrentStep %>" />
    


  • 写将使用模型的价值,不是被公司发布的一个自定义的帮手

  • Write a custom helper which will use the value of your model and not the one that's being POSTed

    这篇关于Hiddenfor没有得到从视图模型正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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