How to post an object from the view model?

Go To StackoverFlow.com

2

I was hoping this would work :( When debugged the hidden input seems to point to an object but in the post nothing shows up. Here is what I tried (note that I am trying for brevity so this is an example)

Model

public class myViewModel
{
 public MyObject MyObject { get; set; }
 public int MyNumber { get; set; }
}

Controller

public ActionResult displaySimpleView()
{
 var mVM = new myViewModel();
 mVM.MyObject = //let MyObject be filled with 10 fields of data
 return View(mVM);
}

View

@model namespace.myViewModel

//display the fields of data

@using (Ajax.BeginForm("Complete", ajaxOpts))//simple Ajax Options not really relevant
{
@Html.ValidationSummary(true)

@Html.HiddenFor(m => m.MyObject)
@Html.EditorFor(m => m.MyNumber)

<p><input type="submit" value="Go" /></p>
}

Controller Again

[HttpPost]
public ActionResult getMyObject(myViewModel mVM)
{
 mVM.MyObject is null here.
 mVM.MyNumber has a value.
 return RedirectToAction("someGetAction");
}

How can I pass MyObject to getMyObject? I would prefer to not have to have a hidden field for each property and then remap because some of those properties are nested objects.

2012-04-04 23:40
by Travis J
Does any HTML get generated for your MyObject? It probably can't represent the object, meaning when it posts it doesn't have any data to pass to the action. I have several question, like why data you are stuffing into this object, and what you are hoping to do. Its likely you need to split each value out into its own property to get this to work though - Tyrsius 2012-04-04 23:50
@Tyrsius - I found a solution. Why am I filling an object with data? Kind of an interesting question in itself isn't it. I don't want my view to know anything about my data so I am making sure that the data I am passing in is contained in an object in my view model. What I am doing is building a complex series of partial views to make it really easy on the user to build something which otherwise would require a lot of navigation. I will not need to split each value. See my answer for my solution - Travis J 2012-04-05 00:00


2

View:

@{
  TempData["passMyObject"] = Model.MyObject;
 }

Controller Post:

var myObject = TempData["passMyObject"];
2012-04-05 00:01
by Travis J
Ads