Teddy Consultant
Teddy Consultant

Reputation: 53

Can not pass the model back to controller from view in ASP.NET MVC. Model is null when received

I have two model classes

public class Item
{
    public string Name;
    public SubItem SubObject { get; set; }
}

public class SubItem
{
    public int Age { get; set; }
    public string Work { get; set; }
}

From my code I have something similar to this

public IActionResult ViewAndSend()
{
        Item item = new Item
        {
            Name = "MyName",
            SubObject = new SubItem
            {
                Age = 29,
                Work = "Microsoft and google"
            },
        };

    return View(item);
}

and my ViewAndSend.cshtml looks like this

@model TestNavigation.Models.Item

<h2>ViewAndSend example</h2>
<p>@(String.Format("{0} {1}", "Name", Model.Name))</p>
<p>@(String.Format("{0} {1}", "Age", Model.SubObject.Age))</p>
<p>@(String.Format("{0} {1}", "Work", Model.SubObject.Work))</p>

@using (Html.BeginForm("SendSubItem", "Home", FormMethod.Post))
{
    @Html.HiddenFor(m => m.SubObject.Age)
    @Html.HiddenFor(m => m.SubObject.Work)

    <input type="submit" value="Next" />
}

My SendSubItem method looks like this

[HttpPost]
public IActionResult SendSubItem(SubItem subItem)
{
        int age = subItem.Age; //age is 0
        var work = subItem.Work; // work is null

        return View();
}

The ViewAndSend.cshtml prints the correct values. However the SendSubItem method gets an object with 0 as Age and null for Work.

Can anyone explain what I am doing wrong?

Upvotes: 1

Views: 714

Answers (1)

mj1313
mj1313

Reputation: 8459

You should use Item as the receiving type.

[HttpPost]
public IActionResult SendSubItem(Item item)
{
    int age = item.SubObject.Age; 
    var work = item.SubObject.Work; 
    return View();
}

Upvotes: 2

Related Questions