Home > Software engineering >  Model binding / ViewModel binding in ASP.Net Core MVC
Model binding / ViewModel binding in ASP.Net Core MVC

Time:03-02

Let's start with simple code:

public class SomeViewModel 
{
    public int State { get; set; }
}

public class SomeController : Controller
{
    public IActionResult DoSomething(int state)
    {
        var viewModel = new SomeViewModel();
        
        if(state % 2 == 0)
            viewModel.State = state * 2;
        else
            viewModel.State = state;
        
        return View("MyView", viewModel)
    }
}

MyView.cshtml:

@model SomeViewModel;

...
    <form method="get" asp-action="DoSomething" asp-controller="Some">
        <input asp-for="State">
        <button type="submit">Save</button>
    </form>

...

I'm making requests:

/some/dosomething?state=4 => input value = 4

/some/dosomething?state=5 => input value = 5

/some/dosomething?state=6 => input value = 6

/some/dosomething?state=7 => input value = 7

but according to my logic in DoSomething action it should be:

/some/dosomething?state=4 => input value = 8

/some/dosomething?state=5 => input value = 5

/some/dosomething?state=6 => input value = 12

/some/dosomething?state=7 => input value = 7

My question is: Why input value is assigned to query param instead of property of passed model object... And second thing I know i can change name of param from state to param1 but maybe there is other way to do it... I've read 2 books about ASP.net core and haven't encounter anything about that.

CodePudding user response:

if your form method is "get" inputs send as query string but if you want to post them as form you shoule post your form and assign type "post" to your form method.

  <form method="post" asp-action="DoSomething" asp-controller="Some">
        <input asp-for="State">
        <button type="submit">Save</button>
    </form>

in this code State bind to your SomeViewModel.

CodePudding user response:

By default if we assign GET to method attribute of form, it exposes the data by query string. To avoid this we set method attribute to POST

<form method="post" asp-action="DoSomething" asp-controller="Some">
        <input asp-for="State">
        <button type="submit">Save</button>
    </form>

Secondly, .NET Core improved the security so official document Recommends that use Model in Post Method like this. (This is optional and best practice. Not mandatory)

public class StateModel 
{
    public int State { get; set; }
}

public class SomeController : Controller
{
    public IActionResult DoSomething(StateModel model)
    {
        var viewModel = new SomeViewModel();
        
        if(model.State % 2 == 0)
            viewModel.State = state * 2;
        else
            viewModel.State = state;
        
        return View("MyView", viewModel)
    }
}
  • Related