MVC Ajax - Parsing Form Submission Return Data
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?
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
To get the actual view html use:
alert(ajaxContext.get_response().get_responseData());
The get_object()
function works only with JSON content.
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.
精彩评论