MVC Cheat Sheet PDF
MVC Cheat Sheet PDF
namespace MyApp.Model {
public class Employee
{
[Key]
[DatabaseGeneratedAttribute(
DatabaseGeneratedOption.Identity)]
public int EmployeeId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string FamilyName { get; set; }
[EmailAddress]
public string Email { get; set; }
[RegularExpression("\\d+\\.\\d+\\.\\d+\\.\\d+",
ErrorMessage = "Invalid IP address format")]
public string IpAddress { get; set; }
Declare navigation properties to be
[NotMapped]
public string FullName
{
get { return FirstName + " " + FamilyName; }
}
}
}
Razor View
@using MyApp.Models
@model Employee
@{
Layout = "~/Views/_Base.cshtml";
ViewBag.Title = "Employee Information";
}
<h2>Employee Information</h2>
<p>These are the details of @Model.FullName:</p>
Write out a value
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
Create a HTML <form> tag
@Html.ValidationSummary()
<div>
First Name: @Html.TextBoxFor(x => x.FirstName) Generate a token to prevent Cross</div>
Site-Forgery-Requests (CSFRs)
<div>
Family Name: @Html.TextBoxFor(x => x.FamilyName)
Show any validation errors
</div>
<div>
Birth Month: @Html.TextBoxFor(x => x.BirthMonth)
Create Text-boxes for Properties of
</div>
the Model
<div>
IP Address: @Html.TextBoxFor(x => x.IpAddress)
</div>
<div>
Full Time:
@Html.DropDownListFor(
Create a Drop-down list for IsFullTime
x => x.IsFullTime,
property of the model
new [] {
new SelectListItem {
Text = "Full Time",
Value = "true",
Selected = Model.IsFullTime
},
new SelectListItem {
Text = "Part Time",
Value = "false",
Selected = !Model.IsFullTime
}
})
</div>
<input type="submit" value="Save Changes" />
Razor comments
Template
<html>
<title>@ViewBag.Title</title>
<body>
<h1>My App</h1>
<div>
@RenderBody()
</div>
<div>
@if (IsSectionDefined("Author"))
{
@: Author Information:
@RenderSection("Author")
}
</div>
</body>
</html>
Controller
...
using System.Data.Entity;
namespace MyApp.Controllers
{
[Authorize]
public class EmployeeController : Controller
{
[AllowAnonymous]
authorization (no need to login)
public ActionResult Index()
{
using (var context = new MyAppContext())
{
var emps = context.Employees
.Include(x => x.Messages).Include(x => x.Department)
.ToList();
Eager loading for view rendering
return View(emps);
(when there is no DbContext)
}
}
[HttpGet]
to retrieve an empty/current form)
public ActionResult Edit(int id)
{
using (var context = new MyAppContext())
{
var emp = context.Employees
.Include(x => x.Messages).Include(x => x.Department)
.Where(x => x.EmployeeId == id).Single();
return View(emp);
}
Use this action when the user POSTs
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, Employee employee)
{
Use HTML Get/Post parameters to
if (ModelState.IsValid)
construct an Employee object
{
if (employee.IpAddress == "127.0.0.1")
{
ModelState.AddModelError("", "Do not use 127.0.0.1");
return View(employee);
Were there any validation errors
}
when creating the Employee object?
else
{
using (var context = new MyAppContext())
{
var oldEmployee = Context.Employees.Find(id);
UpdateModel(oldEmployee);
Add a custom validation error for
@Html.ValidationSummary()
context.SaveChanges();
return View("Details", employee);
}
}
Use HTML Get/Post parameters to
}
update the Employee object
else
{
Return the Details strongly typed
return View(employee);
view (Details.cshtml)
}
}
}
}