Home > DeveloperSection > Forums > Model nested type is null when after modelbinding
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    April-03-2013 2:24 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 1041  View(s)
Rate this:
Hi Everyone!

I have a ViewModel as below:

public class CheckoutViewModel
{
    public string ProductNumber { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
    public Input UserInput;

    public class Input
    {
        public string Email { get; set; }
        public string Phone { get; set; }
    }
}
And an action like this:

[HttpPost]
public ActionResult Index(CheckoutViewModel model)
{
    // ...
    return View();
}
And my model has bound as below:

@model GameUp.WebUI.ViewModels.CheckoutViewModel

@using (Html.BeginForm("Index", "Checkout", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <!-- some HTML -->

    @Html.LabelFor(m => m.UserInput.Email)
    @Html.TextBoxFor(m => m.UserInput.Email)

    @Html.LabelFor(model => model.UserInput.Phone)
    @Html.TextBoxFor(model => model.UserInput.Phone)

    <button>Submit</button>
}
When I submit the form, the UserInput is null. I know ASP.NET MVC is able to bind nested types but in this code is not. Also I can get the Email and Phone 

values by:

var email = Request.Form["UserInput.Email"];
var phone = Request.Form["UserInput.Phone"];
Maybe I do something wrong! It's a simple model binding you can find everywhere in the web.

Thanks in advance!



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    April-03-2013 8:27 AM

Hi Jeet!

change your properties as from below line of code 

public class CheckoutViewModel
{
    public string ProductNumber { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
    public Input UserInput { get; set; }

    public class Input
    {
        public string Email { get; set; }
        public string Phone { get; set; }
    }
}

I hope it resolve your problem

Don't want to miss updates? Please click the below button!

Follow MindStick