Mac Attack
Mac Attack

Reputation: 962

ASP.NET MVC 3 HtmlHelper.Textbox Uses ModelState as a source for value?

I have a textbox that I am trimming the value of server side in the viewModel's setter and verifying that the trimmed value is present:

    <Required()>
    Public Property Name As String
        Get
            Return Me.mName
        End Get
        Set(value As String)
            Me.mName = value.Trim()
        End Set
    End Property

In the controller, I check to see if the ModelState is invalid, and if it is, I show the view again:

    If (Not ModelState.IsValid) Then
        Return View("Locations", viewModel)
    End If

In situations where the trimmed value is blank, I re-display the form to the user. At this point, the non-trimmed values are put into the textbox. I would much prefer the trimmed value.

I was looking through the MVC sourcecode, and I found that at one point in the InputHelper function (used by Html.Textbox(), located in InputExtensions.cs) the code was checking the ModelState for the value, and if it existed, replacing the controller-supplied value.

    string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string));
    tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : valueParameter), isExplicitValue);

I realize that I could fix this by clearing the ModelState in the controller, but I'm just wondering why the MVC Developers chose to have the values in the ModelState supersede the view model values.

Upvotes: 1

Views: 982

Answers (1)

Adam Tuliper
Adam Tuliper

Reputation: 30152

This was designed this way because the assumption is if you are not redirecting to another view after a post .. Hence the post-redirect-get pattern, then there was ideally an error and the current posted values would be shown back to the user for them to fix hence why they are pulled from modelstate. You can ModelState.Clear to work with this but keep that design in mind.

Upvotes: 3

Related Questions