Render view as string when Ajax request to view is made
I have my views render to route requests like /controller/action (for instance, /Page/Create), so pretty classic.
I am creating a form where view will be loaded through AJAX request with jQuery get(), so essentially I need my Views or to be precise, my controller actions, to return plain HTML string when an AJAX request is made to the route that renders the View. I want to use the same views开发者_如何学运维 as for normal requests, so I cannot afford to create any new views.
It is something like calling RenderPartial("MyViewUserControl") but from inside the JS code.
You need to move the HTML strings to partial views, then include the partial views in your regular views (if applicable) and render the partial views in your actions.
You'll probably want to use the Request.IsAjaxRequest()
extension method in the actions.
To get the HTML in Javascript, you can make a normal AJAX request to the action's URL.
There's nothing special you need to do here - just request your action methods with .get() like normal, and set your response type to "html".
$.get('<% Url.Action("MyActionMethod") %>', { },
function(data){
alert("Data Loaded: " + data);
},
"html")
My answer based on SLAks response - I'm archiving this for later reference or to help someone else.
This is my structure:
1) Create.aspx (ViewPage) uses RenderPartial("Tab-CreateEditForm") to render the create/edit form, which is 2) Tab-CreateEditForm.ascx (the partial) 3) Create action that detects what kind of request is being made. If we are making AJAX request we probably don't want to render Create.aspx which is by default and instead rather render Tab-CreateEditForm because it contains only the form tag and fields and NO page directives, head, title and all the other elements that are in Create.aspx.
So the action looks like this:
//
// GET: /Tab/Create/{tabGroupSlug}
[CanReturnModalView]
[Authorize(Roles = "Administrators")]
public ActionResult Create(string tabGroupSlug)
{
Tab tab = new Tab();
if (Request.IsAjaxRequest())
return View("Tab-CreateEditForm", tab); // returns partial
return View(tab); // returns Create.aspx
}
And this is my Edit action which also uses the same technique because the Edit View (Edit.aspx page) also uses the same editing partial control.
//
// GET: /Tab/Edit/{slug}
[CanReturnModalView]
[Authorize(Roles = "Administrators")]
public ActionResult Edit(string slug)
{
Tab editing = (Tab) _repository.GetInstance(slug);
if (Request.IsAjaxRequest())
return View("Tab-CreateEditForm", editing); // returns partial
return View(editing); // returns Edit.aspx
}
精彩评论