4

My model:

    public class VerifyModel
    {
        public string PIN { get; set; }
        public int Attempts { get; set; }
    }

My view:

    @Html.HiddenFor(m => m.PIN)
    @Html.HiddenFor(m => m.Attempts)

On entry into the view, I inspect Model.PIN and Model.Attempts and they contain the correct values passed from the controller, where Attempts is non-zero. The Html rendered is however:

<input id="PIN" name="PIN" type="hidden" value="xxxx" />
<input data-val="true" value="0"  data-val-number="The field Attempts must be a number." data-val-required="The Attempts field is required." id="Attempts" name="Attempts" type="hidden"/>

The value of Attempts is always 0! And I did not specify anywhere that the Attempts field is mandatory.

How do I solve the problem of int properties in the model?

1 Answer 1

5

If I've understood your question correctly, you're having problems with Attempts not incrementing after the form is posted back with an incorrect PIN. If that assumption is correct then you're experiencing this problem because of the way ModelState works.

The short answer to the problem is simply to call ModelState.Remove from your action:

[HttpPost]
public ActionResult YourAction(VerifyModel model)
{
    ModelState.Remove("Attempts");  
    model.Attempts++;  

    return View(model);
}

If you'd like a full explanation of why this is the case, see ASP.NET MVC’s Html Helpers Render the Wrong Value!. Excerpt:

Why?

ASP.NET MVC assumes that if you’re rendering a View in response to an HTTP POST, and you’re using the Html Helpers, then you are most likely to be redisplaying a form that has failed validation. Therefore, the Html Helpers actually check in ModelState for the value to display in a field before they look in the Model. This enables them to redisplay erroneous data that was entered by the user, and a matching error message if needed.

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! StackOverflow needs more responders like you, who figure out what the OP is trying to achieve. all-things-pure.blogspot.sg/2011/08/expert-is.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.