Reputation: 53
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
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