Monday, May 18, 2015

ASP.NET MVC View Model / Model not binding on HTTP Post

Problem Scenario:

I am having an issue that when I post to a controller, I loose model binding and everything in my model is NULL. Here is the code that I am using:
View:

@model Models.StateDTO
@using (Html.BeginForm("AddState", "Home",new {area="Admin" }, FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)


State Name



@Html.TextBoxFor(m => m.State)
@Html.ValidationMessageFor(m => m.State)





}

Model:

public class StateDTO
    {        
        public int Id { get; set; }
  
        [Required]
        public string State { get; set; }      
    }

Controller:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddState(StateDTO state)
        {
            if (state != null && ModelState.IsValid)
            {
                //.....
            }
            return View();
        }

Why is everything in my model (i.e. StateDTO state) NULL?

Solution:

One possible reason for view model is NULL :
·         The name of model in action parameter be the same as one of view model's properties

Ex: Here, same name means case insensitive (State is same as state)

Hence, the correct controller action method should be like below:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddState(StateDTO vwState)
        {
            if (vwState != null && ModelState.IsValid)
            {
                //.....
            }
            return View();
        }

Here, "State" property name in model is different then action parameter i.e."vwState"

Hope this helps... Cheers :)


No comments:

VS Code # Warning - npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead

Error : VS Code - NPM Warning - npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead Solution:  Foll...