In this article you will learn about MVC architecture, Though MVC architectural pattern has been for a long time in software engineering. MVC pattern is there in all most all the languages, but with slight variation, but conceptually it remains the same everywhere.
Here we talk about Asp.net MVC (Model – View – Controller)
MVC separates application into three components - Model, View and Controller. Each component has been designed for different set of responsibility.
Model represents the details of the business object structure, data and business logic. It maintains the data of the application. Model objects are used retrieve and store model state in a database.
Here is an example of how you write a model
public class GuestModel { [Required(ErrorMessage = "Tell us something ...What you want?")] [StringLength(500, ErrorMessage = "10 to 500 characters.", MinimumLength = 10)] public string PostedText { get; set; } [Required(ErrorMessage = "Your name Required")] [StringLength(50, ErrorMessage = "5 to 50 characters.", MinimumLength = 3)] public string GuestName { get; set; } [Required(ErrorMessage = "Email Required")] [EmailAddress(ErrorMessage = "Invalid email")] public string GuestEmail { get; set; } }
View is a user interface (Razor). View display data using model to the user and also enables user to insert, modify, delete the data.
Here is an example of what you write in View, Razor, will capture user data and display data
@model WebTrainingRoom.Models.GuestModel @using (Html.BeginForm("guestform", "controllerName", FormMethod.Post)) { @Html.AntiForgeryToken() <div>@ViewBag.AskqueryActionMessage</div> <div class="s1"> <div>Your Name</div> @Html.TextBoxFor(m => m.GuestName, new { style = "width:300px;" }) <div>@Html.ValidationMessageFor(m => m.GuestName)</div> </div> <div class="s1"> <div>Your Email</div> @Html.TextBoxFor(m => m.GuestEmail, new { style = "width:300px;" }) <div>@Html.ValidationMessageFor(m => m.GuestEmail)</div> </div> <div> <input type="submit" value="Submit Now" /> </div> }
Controller is the mediator, handles the user request. Controller receives the user request then renders the appropriate view with the model data as a response.
This is how you write Controller, notice Get, and Post for same guestform view
[HttpGet] public ActionResult guestform() { GuestModel model = new GuestModel(); return View(model); } [HttpPost] public ActionResult guestform(GuestModel model) { StringBuilder _str = new StringBuilder(); //Insert data into database using (WTRMail email = new WTRMail()) { //Send email } ViewBag.AskqueryActionMessage = "Your query has been sent successfully."; return View(model); }