ASP.NET MVC – Pattern

ASP.NET MVC – Pattern ”; Previous Next The MVC (Model-View-Controller) design pattern has actually been around for a few decades, and it”s been used across many different technologies. Everything from Smalltalk to C++ to Java, and now C Sharp and .NET use this design pattern to build a user interface. Following are some salient features of the MVC pattern − Originally it was named Thing-Model-View-Editor in 1979, and then it was later simplified to Model- View-Controller. It is a powerful and elegant means of separating concerns within an application (for example, separating data access logic from display logic) and applies itself extremely well to web applications. Its explicit separation of concerns does add a small amount of extra complexity to an application’s design, but the extraordinary benefits outweigh the extra effort. The MVC architectural pattern separates the user interface (UI) of an application into three main parts. The Model − A set of classes that describes the data you are working with as well as the business logic. The View − Defines how the application’s UI will be displayed. It is a pure HTML, which decides how the UI is going to look like. The Controller − A set of classes that handles communication from the user, overall application flow, and application-specific logic. Idea Behind MVC The idea is that you”ll have a component called the view, which is solely responsible for rendering this user interface whether that be HTML or whether it actually be UI widgets on a desktop application. The view talks to a model, and that model contains all of the data that the view needs to display. Views generally don”t have much logic inside of them at all. In a web application, the view might not have any code associated with it at all. It might just have HTML and then some expressions of where to take pieces of data from the model and plug them into the correct places inside the HTML template that you”ve built in the view. The controller that organizes is everything. When an HTTP request arrives for an MVC application, that request gets routed to a controller, and then it”s up to the controller to talk to either the database, the file system, or the model. Print Page Previous Next Advertisements ”;

ASP.NET MVC – Data Annotations

ASP.NET MVC – Data Annotations ”; Previous Next DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations. DataAnnotation attributes override default Code-First conventions. System.ComponentModel.DataAnnotations includes the following attributes that impacts the nullability or size of the column. Key Timestamp ConcurrencyCheck Required MinLength MaxLength StringLength System.ComponentModel.DataAnnotations.Schema namespace includes the following attributes that impacts the schema of the database. Table Column Index ForeignKey NotMapped InverseProperty Key Entity Framework relies on every entity having a key value that it uses for tracking entities. One of the conventions that Code First depends on is how it implies which property is the key in each of the Code First classes. The convention is to look for a property named “Id” or one that combines the class name and “Id”, such as “StudentId”. The property will map to a primary key column in the database. The Student, Course and Enrollment classes follow this convention. Now let’s suppose Student class used the name StdntID instead of ID. When Code First does not find a property that matches this convention it will throw an exception because of Entity Framework’s requirement that you must have a key property. You can use the key annotation to specify which property is to be used as the EntityKey. Let’s take a look at the Student class which contains StdntID. It doesn’t follow the default Code First convention so to handle this, Key attribute is added, which will make it a primary key. public class Student{ [Key] public int StdntID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } When you run the application and look into the database in SQL Server Explorer, you will see that the primary key is now StdntID in Students table. Entity Framework also supports composite keys. Composite keys are primary keys that consist of more than one property. For example, you have a DrivingLicense class whose primary key is a combination of LicenseNumber and IssuingCountry. public class DrivingLicense{ [Key, Column(Order = 1)] public int LicenseNumber { get; set; } [Key, Column(Order = 2)] public string IssuingCountry { get; set; } public DateTime Issued { get; set; } public DateTime Expires { get; set; } } When you have composite keys, Entity Framework requires you to define an order of the key properties. You can do this using the Column annotation to specify an order. Timestamp Code First will treat Timestamp properties the same as ConcurrencyCheck properties, but it will also ensure that the database field generated by Code First is non-nullable. It”s more common to use rowversion or timestamp fields for concurrency checking. But rather than using the ConcurrencyCheck annotation, you can use the more specific TimeStamp annotation as long as the type of the property is byte array. You can only have one timestamp property in a given class. Let’s take a look at a simple example by adding the TimeStamp property to the Course class. public class Course{ public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } [Timestamp] public byte[] TStamp { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } As you can see in the above example, Timestamp attribute is applied to Byte[] property of the Course class. So, Code First will create a timestamp column TStamp in the Courses table. ConcurrencyCheck The ConcurrencyCheck annotation allows you to flag one or more properties to be used for concurrency checking in the database, when a user edits or deletes an entity. If you”ve been working with the EF Designer, this aligns with setting a property”s ConcurrencyMode to Fixed. Let’s take a look at a simple example and see how ConcurrencyCheck works by adding it to the Title property in Course class. public class Course{ public int CourseID { get; set; } [ConcurrencyCheck] public string Title { get; set; } public int Credits { get; set; } [Timestamp, DataType(“timestamp”)] public byte[] TimeStamp { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } In the above Course class, ConcurrencyCheck attribute is applied to the existing Title property. Code First will include Title column in update command to check for optimistic concurrency as shown in the following code. exec sp_executesql N”UPDATE [dbo].[Courses] SET [Title] = @0 WHERE (([CourseID] = @1) AND ([Title] = @2)) ”,N”@0 nvarchar(max) ,@1 int,@2 nvarchar(max) ”,@0 = N”Maths”,@1 = 1,@2 = N”Calculus” go Required The Required annotation tells EF that a particular property is required. Let’s have a look at the following Student class in which Required id is added to the FirstMidName property. Required attribute will force EF to ensure that the property has data in it. public class Student{ [Key] public int StdntID { get; set; } [Required] public string LastName { get; set; } [Required] public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } You can see in the above example of Student class Required attribute is applied to FirstMidName and LastName. So, Code First will create a NOT NULL FirstMidName and LastName column in the Students table as shown in the following screenshot. MaxLength The MaxLength attribute allows you to specify additional property validations. It can be applied to a string or array type property of a domain class. EF Code First will set the size of a column as specified in MaxLength attribute. Let’s take a look at the following Course class in which MaxLength(24) attribute is applied to Title property. public class Course{ public int CourseID { get; set; } [ConcurrencyCheck] [MaxLength(24)] public string Title { get; set; } public int Credits {

ASP.NET MVC – Model Binding

ASP.NET MVC – Model Binding ”; Previous Next ASP.NET MVC model binding allows you to map HTTP request data with a model. It is the process of creating .NET objects using the data sent by the browser in an HTTP request. The ASP.NET Web Forms developers who are new to ASP.Net MVC are mostly confused how the values from View get converted to the Model class when it reaches the Action method of the Controller class, so this conversion is done by the Model binder. Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene. Let’s take a look at a simple example in which we add a ‘Create View’ in our project from the last chapter and we will see how we get these values from the View to the EmployeeController action method. Following is the Create Action method for POST. // POST: Employee/Create [HttpPost] public ActionResult Create(FormCollection collection){ try{ // TODO: Add insert logic here return RedirectToAction(“Index”); }catch{ return View(); } } Right-click on the Create Action method and select Add View… It will display the Add View dialog. As you can see in the above screenshot, the default name is already mentioned. Now select Create from the Template dropdown and Employee from the Model class dropdown. You will see the default code in the Create.cshtml view. @model MVCSimpleApp.Models.Employee @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name = “viewport” content = “width = device-width” /> <title>Create</title> </head> <body> @using (Html.BeginForm()){ @Html.AntiForgeryToken() <div class = “form-horizontal”> <h4>Employee</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.JoiningDate, htmlAttributes: new{ @class = “control-label col-md-2” }) <div class = “col-md-10”> @Html.EditorFor(model => model.JoiningDate, new{ htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.JoiningDate, “”, new { @class = “text-danger” }) </div> </div> <div class = “form-group”> @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = “control-label col-md-2” }) <div class = “col-md-10”> @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = “form-control” } }) @Html.ValidationMessageFor(model => model.Age, “”, 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> </body> </html> When the user enters values on Create View then it is available in FormCollection as well as Request.Form. We can use any of these values to populate the employee info from the view. Let’s use the following code to create the Employee using FormCollection. // POST: Employee/Create [HttpPost] public ActionResult Create(FormCollection collection){ try { Employee emp = new Employee(); emp.Name = collection[“Name”]; DateTime jDate; DateTime.TryParse(collection[“DOB”], out jDate); emp.JoiningDate = jDate; string age = collection[“Age”]; emp.Age = Int32.Parse(age); empList.Add(emp); return RedirectToAction(“Index”); }catch { return View(); } } Run this application and request for this URL http://localhost:63004/Employee/. You will receive the following output. Click the ‘Create New’ link on top of the page and it will go to the following view. Let’s enter data for another employee you want to add. Click on the create button and you will see that the new employee is added in your list. In the above example, we are getting all the posted values from the HTML view and then mapping these values to the Employee properties and assigning them one by one. In this case, we will also be doing the type casting wherever the posted values are not of the same format as of the Model property. This is also known as manual binding and this type of implementation might not be that bad for simple and small data model. However, if you have huge data models and need a lot of type casting then we can utilize the power and ease-of-use of ASP.NET MVC Model binding. Let’s take a look at the same example we did for Model binding. We need to change the parameter of Create Method to accept the Employee Model object rather than FormCollection as shown in the following code. // POST: Employee/Create [HttpPost] public ActionResult Create(Employee emp){ try{ empList.Add(emp); return RedirectToAction(“Index”); }catch{ return View(); } } Now the magic of Model Binding depends on the id of HTML variables that are supplying the values. For our Employee Model, the id of the HTML input fields should be the same as the Property names of the Employee Model and you can see that Visual Studio is using the same property names of the model while creating a view. @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = “form-control” } }) The mapping will be based on the Property name by default. This is where we will find HTML helper methods very helpful because these helper methods will generate the HTML, which will have proper Names for the Model Binding to work. Run this application and request for the URL http://localhost:63004/Employee/. You will see the following output. Let’s click on the Create New link on the top of the page and it will go to the following view. Let’s enter data for another employee that we want to add. Now click the create button and you will see that the new employee is added to your list using the ASP.Net MVC model binding. Print Page Previous Next Advertisements ”;