views:

254

answers:

3

I am using MVC Ajax to do a form submission. What I can't get right is to get the Action on the server to return a partial view to the browser.

The form submission looks like this:

<% using (Ajax.BeginForm("Add", "Example", new AjaxOptions { HttpMethod = FormMethod.Post.ToString(), OnComplete = "widgetAdded" } )) { %>

This hits the server and the action gets executed. The JavaScript method 'widgetAdded' that gets executed after the action completes looks something like this:

function widgetAdded(ajaxContext) {
    var response = ajaxContext.get_response().get_object();
    alert(response);
}

If I return a Json result in the action like this, it works - the alert shows the data being passed from the server.

return Json("bob");

Now if I change the action to return a PartialView like this, it doesn't work.

return PartialView("Widgets");

I've tried to interrogate the response object in Firebug, but I can't seem to get the actual view html. Any ideas?

A: 

You could render your partial view to a string, and return the string:

        public static string RenderPartialToString(string controlName, object viewData, object model, System.Web.Routing.RequestContext viewContext)
        {

            ViewDataDictionary vd = new ViewDataDictionary(viewData);
            ViewPage vp = new ViewPage { ViewData = vd };

            vp.ViewData = vd;
            vp.ViewData.Model = model;
            vp.ViewContext = new ViewContext();
            vp.Url = new UrlHelper(viewContext);

            Control control = vp.LoadControl(controlName);

            vp.Controls.Add(control);

            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {

                using (HtmlTextWriter tw = new HtmlTextWriter(sw))
                {

                    vp.RenderControl(tw);

                }

            }

            return sb.ToString();

        }

Code above taken from here

kobusb
This seems like it could work, but it also seems quite messy. Shouldn't we be able to do it without all this extra work?
Jaco Pretorius
A: 

To get the actual view html use:

alert(ajaxContext.get_response().get_responseData());

The get_object() function works only with JSON content.

Darin Dimitrov
The get_responseData returns an empty string for me
Jaco Pretorius
A: 

I did some more research and it seems it's not possible to return a view as the response to a POST action. I looked at the actual response being sent to the client - if I return a string (as Json) the response header actually gets populated - if I return a view the response header is empty.

It seems like the best solution is to simply do another GET (using JQuery) and retrieving the View manually.

Jaco Pretorius