views:

56

answers:

3

I have been developing in ASP.NET MVC for a short while. Up to this point, the controller actions have been fairly simple. Each action returns its corresponding view. However, I recently created an action that I don't necessarily need a page for (the purpose of the action is to work with the database).

My question is - what is the proper thing to do here. At the end of the method, I return Response.Redirect('\Controller\View'), so I go back to another view. Is it possible to not have to return any kind of view at the end of an action? What are the best practices here?

+2  A: 

If you need to redirect a user because they clicked a link then redirect a user.

If your posting with Ajax or another technique and there is no meaningful response change the controller action method to have a return type of void.

jfar
Thanks, jfar! I thought about doing this, but in researching on Google, I got a bit confused about whether this was accepted. From yours, and other answers, it appears that this is okay. (And, yes, it is an Ajax POST.)
JasCav
+1  A: 

If you're posting with AJAX and you don't need to redirect the user or display a new view, you might want to consider returning a string that displays a confirmation message to the user.

Terminal Frost
Thank you. Yeah, I use jQuery to display a fadeIn/fadeOut message letting the user know that the save (AKA, the POST) was successful.
JasCav
A: 

I would say, an action should always handle a HTTP request. If it returns a view or redirects to another action, both is possible.

Consider the following:

[HttpGet] // Handles only GET requests
public ActionResult Edit(int id)
{
     // get entity from repository
     // and create edit model
     return View(editModel);
}

[HttpPost]
public ActionResult Edit(EntityEditModel editModel)
{
     // if ModelState is valid, save entity
     // and if success redirect to index 
     return RedirectToAction("Index");
}

The first action return a view, the second doesn't (only if the ModelState is not valid, then it re-displays the Edit view). And this is absolutely correct to do (it's even recommended). But both actions handle a HTTP request.

Dave