ASP MVC Views
Links
To build the views during build, edit the project file: <MvcBuildViews>false</MvcBuildViews>
Master Pages (Razor: Layout Pages)
These should live in \Views\Shared\
- For ASP Engine, use MasterPages:
<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.CategoryModel>" %> - For Razor Engine, they are called "Layout Pages"
- You have a default @RenderBody()
- Optional sections:
@if (IsSectionDefined("Footer"))
{
@RenderSection("Footer", required: false)
}
else ... - Define the layout in the view or Views/_ViewStart.cshtml
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
One _ViewStart per area.
ViewData/ViewBag and Models
ViewData (MVC1-2)
ViewData is a name/value dictionary available in the View
- Controller Action: ViewData["HelloWorld"] = "Hello World";
return View(); - View: <p><%: ViewData["HelloWorld"] %></p>
Strongly typed views:
- Controller Action: return View(category);
- View: <%@ Page Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.CategoryModel>"
- View: <p><%: Model.Name %></p>
ViewBag (MVC3)
ViewBag is a strong-typed wrapper for ViewData (in MVC3+)
@model (MVC3)
In MVC 3 you can have a strong-typed model. Simple models may use the business/data entities directly (or an IEnumerable of them), but you'll probably want a ViewModel specific to the screen (it's also more secure).
@model MvcApplication1.Models.CategoryModel
TempData (MVC2)
The TempDataDictionary (TempData["x"] = "y") is just Session, so can be used with RedirectToAction.
If your controller action has parameters e.g. public ActionResult Edit(int id) then that id is used, not the model.Id!
To fix, do a
ModelState.Clear();
in your action.
Partial Views (User controls)
Common partial views should live in \Views\Shared\
- For ASP Engine, add a new View user control (*.ascx), accessed either with Html.Partial, or via the controller as Html.Action
- For Razor Engine, create a partial view (_*.cshtml - the underscore prefix makes it hidden)
@Html.Partial("_HelloWorld")
You can also use @Html.Action("_HelloWorld" which calls a controller action.
Delete-Cancel buttons
A typical CRUD form may have a row of buttons for Save-Cancel-Delete.
- You can have three submit buttons with an if/else in the Action, but that's not very neat.
- You can't wrap the cancel and delete buttons in nested forms (not allowed in HTML).
- Links, especially for delete, are problematic.
- The input/submit formaction="" attribute is perfect but IE 10+ only (and not Android at time of writing)
- The easiest solution is javascript (using input type=button) and you can hook up your HttpPost Delete action.
$("#Cancel").click(function() {
window.location = "@Url.Action("Index")";
});
$('#Delete').click(function() {
if(confirm("@WebApp.Resources.Crud.AreYouSure")) {
var form = document.forms[0];
form.action = "@Url.Action("Delete")";
form.submit();
}
});