Behavior while passing objects inside objects in asp.net mvc?

66 Views Asked by At

I am sure everyone has come across this but I thought will ask this anyways. So here is what I have -

public class ABC
{
  public int x;
  public int y;
  public XYZ obj;
}
public class XYZ
{
 int x1;
 int y1;
}
public ActionResult Test1()
{
  ABC model= new ABC();
  model.x=1;
  model.y=2;
  ABC.obj= new XYZ();
  model.x1=12;
  obj.y2=34;
  return View(model);
}
[HttpPost]
public ActionResult Test1(ABC model)
{
 //does not get XYZ obj
}
View- 
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Models.ABC>" %>
   <% using (Html.BeginForm())
   {%>
    //stuff here
        <%:Html.HiddenFor(model => model.obj)%>
   <%}%>

If I do the hidden fields for explicitly for XYZ's fields x1 and y1 then I get back those values. Like this - <%:Html.Hidden("Model.obj.x1",Model.obj.x1)%> I guess this is expected behavior but am I missing anything here ?

1

There are 1 best solutions below

0
On

Well, for one thing, your "inherits" attribute is wrong. Instead of

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="Models.ABC" %>

It should be

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<Models.ABC>" %>

If you want to use Models.ABC as your model. For another, the action methods you posted aren't even compilable, so it's difficult to tell what the real problem might be.

Sending composite objects like this works just fine for me, so there is most likely an issue with your implementation.

Update

Values for any persisted model properties have to be POSTed back from the editor page, which means they need to be stored in form fields. If the page generator isn't creating fields for those values (and I'm not sure it should - it would make more sense to me to include a partial view for nested objects), you'll need to add fields that are either editable or hidden.