Pass viewmodel to ajax controller action that returns partial with that model?
I have a view that is strongly typed. Inside this view i have jqueryui tabs, that when clicked call my Controller and return a partial view
("#tab0").load('@Url.Action("ProfileImage", "User")');
public ActionResult ProfileImage()
{开发者_运维百科
return PartialView("_ProfileImage");
}
What I'd like to do is pass the model from the "parent" view to the controller which can then bind it to the partial when it is returned:
("#tab0").load('@Url.Action("ProfileImage", "User", new {model=model})');
public ActionResult ProfileImage(UserViewModel model)
{
return PartialView("_ProfileImage", model);
}
Is this possible? how is this normally done? Where you have the model data in one view and you'd like to pass it to a asynchronously loaded partial view?
You could create a ToJson method on your viewmodel, which could be something like this:
public IHtmlString ToJson()
{
return MvcHtmlString.Create(Json.Encode(this));
}
It just serializes the viewmodel into a json. The IHtmlString returntype makes sure the output isn't encoded in your view. The call to your controller would be something like this:
("#tab0").load('@Url.Action("ProfileImage", "User", new {model=model.ToJson()})');
The json modelbinder can recreate the viewmodel on the serverside. You probably run into some problems along the way, but nothing unsolvable I guess.
精彩评论