Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

asp.net mvc - Hiddenfor not getting correct value from view model

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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. Remove the value from the modelstate:

    [HttpPost]
    public ActionResult Foo(SomeModel model)
    {
        ModelState.Remove("CurrentStep");            
        model.CurrentStep = Steps.SomeNewValue;
        return View(model);
    }
    
  2. Manually generate the hidden field

    <input type="hidden" name="NextStep" value="<%= Model.CurrentStep %>" />
    
  3. Write a custom helper which will use the value of your model and not the one that's being POSTed


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...