ViewModels - Tarostar/SimpleNetBlog GitHub Wiki
Create a folder: ViewModels
The view model acts as a contract between the controller and view, and represents the data to display in a view (both static and form input values).
- Every single action within every single controller should have a view model.
- One file with all view models for controllers, e.g. a file called Auth, but with multiple classes within it.
- Having a view model per action is best practice.
- The class is the contract between the view and controller, e.g.: properties such as
public string Username { get; set; }
The naive way is to create a form on the page (e.g. login page) that matches the properties in the form model.
public ActionResult Login(AuthLogin form)
{
return Content("Hi there " + form.Username);
}
However, the only reason this works is because the form Username happens to match the name used in the HTML form, e.g. name="Username"
Instead strongly type it. Strongly typed views are views that have a view model associated with it (e.g. @model SimpleBlog.ViewModels.AuthLogin
.
Then we can use:
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Username)
@Html.EditorFor(x => x.Username)
</div>
`<div>`
`@Html.LabelFor(x => x.Password)`
`@Html.EditorFor(x => x.Password)`
`</div>`
`<div>`
`<input type="submit" value="Login" />`
`</div>`
}
This will generate the form with the properties in the ViewModel class, e.g. AuthLogin.
In the ViewModels c# file (e.g. ViewModels->Auth.cs) Data Annotation can be used to set data type, required fields, etc. e.g.: [Required, DataType(DataType.Password)]
In the controller (like AuthController.cs) you can have multiple methods, and using [HttpPost], etc. explicitly tells ASP.NET which method to use. So adding a new public ActionResult Method(xxx)
method we can do validation on the Required data annotation above, e.g.:
[HttpPost] // explicitly directs POST here
public ActionResult Login(AuthLogin form)
{
if (!ModelState.IsValid)
return View(form);`
`if (form.Username != "Claus")`
`{`
`ModelState.AddModelError("Username", "Username or password isn't correct");`
`return View(form);`
`}`
return Content("The form is valid");
}