0

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?

billy jean
  • 1,399
  • 4
  • 25
  • 45

1 Answers1

0

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.

Robin van der Knaap
  • 4,060
  • 2
  • 33
  • 48
  • Hey thanks, isn't there a toJson included in .Net somewhere or does it not work? – billy jean Aug 23 '11 at 22:27
  • Not that I know of, but in this case you definitely want to return a IHtmlString or your model gets screwed up due to encoding. – Robin van der Knaap Aug 23 '11 at 22:31
  • There's this thing Json.Encode .. seems to encode it. But i wonder if using this jquery load function is the wrong way to handle this. Maybe i should build an ajax query?? – billy jean Aug 23 '11 at 22:35
  • The load function is the simplest, but if you want a smoother user experience you should let the controller only return a json result and built the view using jquery templates (http://api.jquery.com/category/plugins/templates/) In that case you have to use the ajax query. – Robin van der Knaap Aug 23 '11 at 22:39
  • actually looks like the issue might be the use of @Url.Action() .. i am new to mvc and looks like this helper builds a url with querystring paramaters.. the controller function i am using is expecting a JSON view model. so i am guessing the querystring URL is not going to work. – billy jean Aug 23 '11 at 22:40
  • yup, I overlooked that, you have to use ajax query after all. – Robin van der Knaap Aug 23 '11 at 22:46