I am new to ASP.NET MVC. Could you explain what is the difference between ActionResult and ViewResult? Does it matter if use ActionResult as the return type for my actions instead of view.
And what do you mean by rendering a view and returning a view?
These are two actions. Would it matter if i change the Index() type from ViewResult to ActionResult?
public ViewResult Index()
{
var customers = GetCustomers();
return View(customers);
}
public ActionResult Details(int id)
{
var customer = GetCustomers().SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}
2
Answers
Here is the link for the same question about ActionResult and ViewResult Difference Between ViewResult() and ActionResult()
TLDR: ActionResult is an abstract class, and ViewResult derives from it. In most cases you should use ActionResult as a method return type because it’s more convenient and flexible (you can return any class that derives from AcionResult). But if you will use ViewResult as the return type for a method you have to return the ViewResult or any different class that derives from it
A ViewResult is a type of ActionResult. The View helper method in this line
return View()
is actually just shorthand forreturn ViewResult()
. So, you are returning a ViewResult and because that is a type of ActionResult, you can set the return type of your method (for example Details) to ActionResult.Here is more information about the ViewResult class https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.viewresult?view=aspnetcore-7.0
For the other part of your question, rendering vs returning a view. As far as I know, a view is returned in the action response method (as you have shown). A view is only rendered when you are using a partial view and want to render the partial view within another view. In this case, the partial view is rendered in the view file itself. So you ultimately still only need to return the view in the action response method, as the partial view will be rendered within it.
For more information on rendering partial views, look here: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-7.0