Hiddenfor not getting correct value from view model

前端 未结 4 1726
傲寒
傲寒 2020-12-02 16:55

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.

<         


        
相关标签:
4条回答
  • 2020-12-02 17:14

    My solution was to use Darin's second option, because option 1 (clearing from the model state) means hard coding a string (and the naming convention can be tricky with complex models), and wanted to avoid option 3 because I already have so many custom helpers.

    <input type="hidden" name="@Html.NameFor(x => Model.SomeId)" value="@Model.SomeId" />
    

    Just a reminder that you can use Html.NameFor to keep things clean.

    0 讨论(0)
  • 2020-12-02 17:18

    Make sure you model property has a "set" operator.

    This won't get updated on post-back:

    @Html.HiddenFor( m => m.NoSeq)

    public Class MyModel
    {
        int _NoSeq;
        public NoSeq
        {
            get { return _NoSeq };
        }
    }
    
    0 讨论(0)
  • 2020-12-02 17:32

    Let me add this simple reminder as well in addition to all of these correct answers.
    Watch your syntax!
    In Razor, both of these statements compile with no errors.

     Html.HiddenFor(i => i.Id); //Compiles, but doesn't bind 
    @Html.HiddenFor(i => i.Id); //Compiles and bind 
    

    I was struggling to bind my Id and post it back to an Action.
    Though it was always empty.
    I was missing the @ symbol!

    0 讨论(0)
  • 2020-12-02 17:38

    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

    0 讨论(0)
提交回复
热议问题