Why MVC uses ModelState for the supplied model in GET

When MVC launches ActionMethod, it populates the dictionary ModelStateand uses it ModelBinderto assemble parameters ActionMethod, if any. He does this both for GETand for POST. Which makes sense.

After successful execution, the ActionMethodview is displayed using a razor, which in my case uses as many calls as possible HtmlHelper. Until now, you might be thinking, "Yes, I know how MVC works." Wait, I'm getting there.

When we use, for example, @Html.TextFor(m => m.Name)MVC uses the code that may be here to render the tag.

The interesting part is at the end of the file, where we find:

switch (inputType)
{
    case InputType.CheckBox:
        // ... removed for brevity
    case InputType.Radio:
    // ... removed for brevity
    case InputType.Password:
    // ... removed for brevity
    default:
        string attemptedValue = 
               (string)htmlHelper.GetModelStateValue(fullName, typeof(string));
        tagBuilder.MergeAttribute("value", attemptedValue ?? 
               ((useViewData) 
                  ? htmlHelper.EvalString(fullName, format) 
                  : valueParameter), isExplicitValue);
        break;
} 

, ModelState Model. POST, , , , MVC , . , StackOverflow , . POST, ,

GET! .

:

public ActionResult GetCopy(Guid id)
{
    var originalModel = this.repository.GetById(id);
    var copiedModel = new SomeModel
    {
        Id = Guid.NewGuid(),
        Name = originalModel.Name,
    };

    return this.View(copiedModel);
}

:

    @Html.TextBoxFor(m => m.Id)
    @Html.TextBoxFor(m => m.Name)

, GUID Id . , Id action GET, ModelState Id.

, , :

  • ActionMethod -
  • ModelState ActionResult Modelstate.Clear()
  • ModelState Model .

: GET POST. - ModelState Model GET.

+4
1

DefaultModelBinder GET POST. MVC , , , ModelState GET ( , POST), GET.

, , , , ( int), . GET

public ActionResult Search(SearchViewModel model)

, GET .

A ( ) , javascript, "TWO" . , , ModelState ( "TWO" int), . .

ModelState, 0 "Two", ( 0 !) , ?)

+3

Source: https://habr.com/ru/post/1692032/


All Articles