Reputation: 34632
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?
Upvotes: 4
Views: 2014
Reputation: 1
You can use the tilde syntax to provide the full path to the view, as follows:
Specifying a View
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start
your ASP.NET MVC application.";
return View("~/Views/Example/Index.cshtml");
}
When using the tilde syntax, you must supply the file extension of the view because this bypasses the view engine’s internal lookup mechanism for finding views.
Upvotes: 0
Reputation: 5944
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.
Upvotes: 0
Reputation: 5544
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.
Upvotes: 1
Reputation: 24754
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.
Upvotes: 2