Correct approach to avoid rendering view in Action
I currently use an ajax post back to an action to create a new database object and then return the rendered html for a view of that object. I then inject that html into the page.
I was wondering, since MVC 开发者_StackOverflowdoes easily allow you to render views to HTML from within controllers, if there was a better (or more correct) approach to the problem.
(I currently use this code to render the view as html in the action).
Any and all ideas appreciated.
As a matter of fact there is. Just return a partial view.
public ActionResult AjaxStuff()
{
// do whatever
var model = ...;
return PartialView(model);
}
It's true you can render it using PartialView or doing it custom via JSON (PartialView is just so much easier!).
It really depends on your implementation and choices regarding graceful degradation.
What I usually do is:
[HttpGet]
public ActionResult SignIn()
{
//Check if it is an AJAX request
if (Request.IsAjaxRequest())
return PartialView();
else
return View();
}
So it is possible to get your cake and eat it too.
Truth be told there are various ways to get this view from the server. You could use the asp.net mvc ajax js library, use .getJSON or .ajax, or even do it via JQuery using .load: http://api.jquery.com/load/
You can render a PartialView as the other answer suggested or return JsonResult and populate your HTML from the JSON data. Your call.
精彩评论