ASP.NET MVC 5 Fundamentals
Hello Im Fabian Calsina, Im writing this post as a complement to the repository mentioned below.
All the theory described here was implemented in the current repository https://github.com/Fabho/dotnet_mvc_learning_repo
It is a .Net mvc project that uses Entity framework and code first pattern to generate a small database. The project can be debugged from Visual Studio or deployed to an ISS server if you have an SQL database installed and a user with db owner permissions.
Model View Controller (MVC) is an design pattern pattern that separates an application into three main layers: the model, the view, and the controller.
.Net has its own implementation with several additional features. As can be seen in the image.
-Everything starts with a user action in the View that translates into a request url.
-A .net MVC Controller attends the request, obtaining and modifying the Model as necessary.
-The Controller returns the Model and sends the information to the View.
-The View is updated.
In summary a Controller respond a url request and return a View that displays some Model.
To create an MVC project we are going to
New File
Create new Project
Filter and select MVC project
Check the option place solution and project in the same directory
Click on Create
Note that we have 3 folders called Model, View and Controller.
References tells C# compiler where to look when it's trying to resolve symbols. We can reference other projects, libraries.
App_Start contains default configuration files from the framework.They can be updated as required.
Content contains bootstrap css files which are created by .Net
Controllers contains the MVC controllers for the project.
Models contains the Models for the project
Scripts contains jquery files which are created by .Net.
Views contains razor views.
Global.asax contains global configuration that define what the app does when it start.
Web.config contains xml settings for the project. We can create any required property in <appSettings> tag .Here I have created the DB connectionstrings.
In code we can access the properties
From C# top web, MVC gave us an assembly .ddl (Intermediate Language)
Configuration.Manager
@model OdeToFood.Data.Models.Restaurant @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Restaurant</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Cuisine, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EnumDropDownListFor(model => model.Cuisine, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Cuisine, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Razor is dynamic, if we want to work with typed values we can use @model that tells the view that the model is from certain type. This view is working with the files defined in the Model folder.
We can access model properties using @Model. Note the Uppercase M.
MVC Controllers
MVC requests use route rules to map the requests
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
Request example http://localhost/Restaurants . {controller}/{action} is equal to RestraurantController and action equals to Index.
public class RestaurantsController : Controller { // GET: Restaurants private readonly IRestaurantData db; public RestaurantsController(IRestaurantData db) { this.db = db; } [HttpGet] public ActionResult Index() { var model = db.GetAll(); return View(model); } }
Use of query strings
We can access url query strings using
HttpContext.Request.QueryString["name"]
public ActionResult Details(string name)
Controller is a component that respond to some event. :Net has 2 type of controllers
MVC controller from Systen.Web.MVC;
WebApi controller from System.Web.Http;
WebApi controllers are designed to work with rest events GET, POST, PUT, PATCH, etc.
Sometimes classes are called entities because its how they are persisted in DB. In other scenarios a class is not exactly like an entity and its common to use ViewModels.
.Net MVC use model binding using ActionResult to match the controller and views.
[HttpGet]
public ActionResult Index()
{
var model = db.GetAll();
return View(model);
}
Model Validation
We can validate model using ModelState property inherit from controller or use data annotations.
public int Id { get; set; } [Required] [MaxLength(255)] public string Name { get; set; }
Entity framework connection
Entity framework is an ORM(Object Relationship Mapper). To install it:
Rich click in the project.
Click on Manage Nuget packages.
Search for Entity Framework
Install it.
To use it we require a class derived from Entity Framework called DBContext
public class OdeToFoodDbContext : DbContext { public DbSet<Restaurant> Restaurants { get; set; } }
We are ready to use it
public class SqlRestaurantData : IRestaurantData { private readonly OdeToFoodDbContext db; public SqlRestaurantData(OdeToFoodDbContext db) { this.db = db; } public void Add(Restaurant restaurant) { db.Restaurants.Add(restaurant); db.SaveChanges(); } public void Delete(int id) { var restaurant = db.Restaurants.Find(id); db.Restaurants.Remove(restaurant); db.SaveChanges(); } public Restaurant Get(int id) { return db.Restaurants.FirstOrDefault(r => r.Id == id); } public IEnumerable<Restaurant> GetAll() { return from r in db.Restaurants orderby r.Name select r; } public void Update(Restaurant restaurant) { var entry = db.Entry(restaurant); entry.State = EntityState.Modified; db.SaveChanges(); } }
Razor notes
We can define c# code in razor views using @{}.
@razor renders all the content to html.
Default MVC Views starts with _ViewStart.chtml where the main _Layout.cshtml is called.
We can share data from our controller to our view using ViewBag and TempData.
ViewBag and TempData are dynamic. TempData saves data until the next request
We can render partial views using @RenderSection(“view”, params)
<div class="container body-content"> @if(TempData["Message"] != null) { <div class="alert alert-info">@TempData["Message"]</div> } @RenderBody() <hr /> <footer> <p>© @DateTime.Now.Year - My ASP.NET Application</p> @RenderSection("footer", required: false) </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)
Deployment
We can deploy to ISS, Azure App Services, File System with Visual Studio.
Steps:
Right click in the project.
Click on publish
Create or Select a profile
Publish it
I will deploy to an IIS local server
Steps:
Open IIS
Right click to websites
Click Add website
Click ok
Go to localhost
Comentarios
Publicar un comentario