In an ASP.NET Core controller, View creates a result that tells Razor to render a view. The method is inherited from Controller. An action can return View() when it needs only the default view; Razor uses the action name to select a .cshtml file. For example, HomeController.RsvpForm selects Views/Home/RsvpForm.cshtml. section 3.2.3 section 7.1.7
Choose arguments according to what the response needs:
- View(): select the action's default view without supplying a view model. section 3.2.3 section 21.2.4
- View(model): keep the default view and pass it data. A response-list action can filter repository data with LINQ, then pass the results to a Razor view that renders table rows. section 3.2.8
- View("Watersports", product): select a named view and supply a model. The view engine resolves the name to a file; the action need not include its folder or .cshtml extension. section 21.2.4
Select a view from an action
A HomeController.Index action can return View("Watersports", product) for one product category and View(product) otherwise. Create Watersports.cshtml in Views/Home before requesting the action: selecting a view whose file does not exist produces an error. When resolving a view, Razor looks in Views/[controller] and then Views/Shared, so a shared view can be used by multiple controllers. section 21.2.4
Listing 21.9 Selecting a view in the HomeController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;
namespace WebApp.Controllers {
public class HomeController : Controller {
private DataContext context;
public HomeController(DataContext ctx) {
context = ctx;
}
public async Task<IActionResult> Index(long id = 1) {
Product? prod = await context.Products.FindAsync(id);
if (prod?.CategoryId == 1) {
return View("Watersports", prod);
} else {
return View(prod);
}
}
}
}
The controller listing shows both branches of the named-versus-default view choice while passing the same product as the model. section 21.2.4
A view component also has a View method, but its result renders a partial view inside a parent view. With no view name, Razor looks for Default.cshtml in component-specific locations, not the controller action's same-named view. Keep the two uses separate when a missing-view error lists unexpected search paths. section 24.4.1
