Showing posts with label ASP.net MVC. Show all posts
Showing posts with label ASP.net MVC. Show all posts

Explicit Model binding in Asp.net MVC with example





  1. Model binding allows you to map and bind the HTTP request data with a model.
  2. Model binding implicitly goes to work when an action method has parameter.
  3. Model binding can be explicitly invoked using UpdateModel and TryUpdateModel method.

In this article we will discuss if not implicitly how we can trigger Model binding explicitly.

Why Model binding explicitly?

Sometimes there are cases where we need to trigger the model binding process explicitly. The model binding fills the model class with the form values and also outputs ModelState as by-product, that means if the model class has Data Annotation attributes applied for validation, the model binding validates the model properties against Data Annotation attributes and updates ModelState accordingly. If the validation result is success then the ModelState is true else Vice Versa.

So, in short we know we can trigger explicit model binding for filing model object and also to validate model values if Data Annotation attributes are used.

How Model binding explicitly?
MVC provides two methods which accomplished the task of model binding.

  1. UpdateModel
  2. TryUpdateModel

Both the methods perform same task of explicit model binding, only difference is that the UpdateModel method throws exception if ModelState is not valid and TryUpdateModel not.

How to use these methods?

Lets have a model first. We will use a simple Register model class.

Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace SampleRegisterForm.ViewModel
{
    public class Register
    {
        [Required(ErrorMessage="FirstName is Mandatory !!")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "LastName is Mandatory !!")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Email is Mandatory !!")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is Mandatory !!")]
        public string Password { get; set; }

        [Required(ErrorMessage = "Confirm Password is Mandatory !!")]
        [Compare("Password")]
        public string ConfirmPassword { get; set; }
    }
}
    

The above is our model. We have referred this model class in our View. We will rendering controls for the properties of model inside a form. On submit the form will be posted to controller and there we will perform explicit model binding.

View:
@model SampleRegisterForm.ViewModel.Register
@{
    ViewBag.Title = "Register";
}

<h2>Register</h2>

@using (Html.BeginForm())
{
    @Html.EditorForModel("Register")
    <br />
    <br />
    <input type="submit" value="Submit" />
    <input type="reset"  value="Reset" />
}
    
In the view, we have referred Register model and rendered a form using BeginForm helper. We have rendered controls for model properties using EditorForModel helper. We have two buttons i.e. submit and reset.

UpdateForModel:
[HttpPost]
        public ActionResult Register(FormCollection collection)
        {
            SampleRegisterForm.ViewModel.Register register = new SampleRegisterForm.ViewModel.Register();
            try
            {
                UpdateModel(register);
            }
            catch (Exception e)
            {
                return View(register);
            }
            return View();   
        }
    
We have wrapped UpdateModel method inside a try block. The UpdateModel throws exception if model state is not valid. When the model state is not valid, the UpdateModel throws exception and in catch block we are returning model with errors to the view.

TryUpdateModel:
[HttpPost]
        public ActionResult Register(FormCollection collection)
        {
            SampleRegisterForm.ViewModel.Register register = new SampleRegisterForm.ViewModel.Register();
            if (TryUpdateModel(register))
            {
                return View();
            }
            else
            {
                return View(register);
            }
        }
    
The TryUpdateModel method returns true or false based on the ModelState.

So, this is how you can use UpdateModel and TryUpdateModel for explicit model binding.

Model Binding in Asp.net MVC Razor with example


  1. Model binding is an interesting feature in Asp.net MVC.
  2. It allows you to map and bind the HTTP request data with a model.
  3. The Model Binding reduces the effort to get posted values from the request.
  4. In this article we will see why we need Model binding and how we can achieve it.


Demo

Why Model Binding ?
The first question came to your mind would be why to use Model binding ? How it will better or facilitate coding. We will understand this with an example.

We have an Employee Registeration form, the employee fill in details and clicks on submit button.
In order to save values enter by employee we post form to server on submit click, then by using Request object or by using FormCollection object we fetch values out of it as shown below:



As we can see in above screenshot we have to write so much of code to fetch 5 values from posted form. Suppose your form has 20 fields, then you have to write possibly 20 lines to get all values, which also involves type casting.
                                                     The Model binding makes it easier to get the form values. Lets see how. We must be using a Model in our View.

The left part in the screenshot is out ViewModel and we have referred this ViewModel on our View as shown on right. When the form is posted on submit click, we can accept object of this ViewModel as parameter.


So, as we have seen by just accepting a parameter of class which is reffered on View as ViewModel, all the properties are filled. This is magic of Model binding. It reduces the lines of code and associated TypeCasting and makes it very easy to get posted values.

How Model Binding works ?
The next question on your mind would be How this magic thing works? Lets discuss this.
When we have an action with parameter, the MVC runtime uses a model binder to build the parameter. The MVC runtime uses workhorse as DefaultModelBinder. The Asp.net MVC allows us to have multiple model binders registered in the MVC runtime for different types of model.
                                             In case of EmployeeViewModel object, the default model binder inspects the EmployeeViewModel and finds all the Employee properties available for binding. The default model binder can automatically convert and move values from the request into an EmployeeViewModel object. In simple words, when the model binder sees an EmployeeViewModel has a Name property, it looks for a parameter named "Name " in the request. The model binder uses components known as value providers to search for values in different areas of request. The model binder can look at route data, the query string, the form collection.

Whats more in Model Binding ?
Till now we saw example for complex type i.e. EmployeeViewModel which is a class. Similarly model binding also works with primitive types, collections and complex types. We will see example for each of them.

Lets start it !!

Primitive types:
Primitive types are the basic data types like int, short, long etc. We will also include example for string in this type. Lets have a complete new example. We have a simple form with two controls one accepting Name and other Age.

View:

@{
    ViewBag.Title = "Index3";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index3</h2>


@using (Html.BeginForm())
{
    <text>Name:</text>@Html.TextBox("Name")<br /><br />
    <text>Age: </text>@Html.TextBox("Age")<br /><br />

    <input type="submit" value="Submit" />
}
    

The above View will render two textboxs with Name and Age as their name attribute inside a form. When submit is clicked the form is posted to controller method.

Controller:

[HttpPost]
        public ActionResult Index3(string Name,int Age)
        {
            return View();
        }
    
At the action method we have accepted two parameters having name same as defined inside form on View. When the form is posted the model binder inspects the action method parameters, search them in the request and binds it with value in the request. If the parameter name at the action method and control's name property on view differs then model binding will not work to get the value.

The above screenshot from the Network section of Developer tool. Check the Form Data section, it shows two form values posted Name and Age.



Below screenshot shows how the parameters are send when form is posted. 


This sums up the model binding for primitive type. Lets start with collections.

Collections:

In order to demonstrate this example, we will render List of employees on View. The user can udpate values for all of them and on posting form we will bind the list of employees.

View:


@model List<ModelBindingDemo.ViewModel.EmployeeViewModel>
@{
    ViewBag.Title = "Index1";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index1</h2>


@using (Html.BeginForm())
{
    if (Model != null)
    {
        for (int i = 0; i < Model.Count; i++)
        {
        
    <div>
    <table>
    <tr>
    <td>@Html.LabelFor(m => m[i].Name)</td>
    <td>
    @Html.EditorFor(m => m[i].Name)</td>
    </tr>
    <tr>
    <td>@Html.LabelFor(m => m[i].Designation)</td>
    <td>@Html.EditorFor(m => m[i].Designation)</td>
    </tr>
    <tr>
    <td>@Html.LabelFor(m => m[i].City)</td>
    <td>@Html.EditorFor(m => m[i].City)</td>
    </tr>
    </table>
    </div>    
        }
    }   
    <input type="submit" value="Submit" />
    }
    
As we are rendering list of employees, we need to refer model of type List in the View. We have referred Model of type List of EmployeeViewModel as you can see in above code.

Controller:

public ActionResult Index1()
        {
            List<EmployeeViewModel> list = new List<EmployeeViewModel>();
            list.Add(new EmployeeViewModel { City = "City1", Designation = "Sw 1", Name = "Name 1" });
            list.Add(new EmployeeViewModel { City = "City2", Designation = "Sw 2", Name = "Name 2" });
            list.Add(new EmployeeViewModel { City = "City3", Designation = "Sw 3", Name = "Name 3" });
            return View(list);
        }

        [HttpPost]
        public ActionResult Index1(List<EmployeeViewModel> listEmp)
        {
            return View();
        }
    
The first action method prepares a List of employees and send list to View. The second action method is one to which form will be posted. In this action method we are accepting object of  List of type EmpoyeeViewModel. When the form is posted by us after making changes everything will be captured in the list object at client side.

In case of collection the form is posted in above manner with respect to the controls rendered on View. The Model binder detects properties with [0] belongs to same object and [1] belongs to other. So, using the count the model binder is able to bind the collection types.

Instead of using default Model binder, we can create and register multiple model binders for multiple models as per the requirement. We will discuss about Custom Model binding in other article.

Interesting Facts about Model Binding

  1. ASP.NET MVC Model binding allows you to map HTTP request data to a model.
  2. The MVC runtime uses DefaultModelBinder named workhorse to build the parameters.
  3. Model binding implicitly goes to work when an action method has parameter.
  4. Model binding can be explicitly invoked using UpdateModel and TryUpdateModel method.
  5. The by-product of Model binding is ModelState.


So, we came to the end of this article for Model binding. We hope this article proved useful for you. Please share your feedback in comments section.

Enabling client side Data Annotation Validation MVC Razor


  1. Data Annotation makes it easy to validate your model.
  2. Most of the time we implement the validation at server side, i.e. the form is posted to the server and if the model is invalid the response is sent back to the client and user is displayed with error messages.
  3. The same feature can be achieved at client side, that means the form will be validated at client side, before it is posted to the server.
  4. If the form validation passes, the form is posted otherwise the error message is shown.
  5. In this article we will see how to enable the client side validation.

Watch Video

In order to demonstrate, I need to have a ASP.NET MVC project, a controller, couple of Action methods, View and most important a Model. Lets get started.

Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace DataAnnotation.ViewModel
{
    public class RegisterViewModel
    {
        [Required]
        public string FirstName { get; set; }

        public string LastName { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        [Required]
        public string ConfirmPassword { get; set; }
    }
}
    

We have a Register class as Model. We have defined few properties and marked some of them with Required Data Annotation attribute.

View
@model DataAnnotation.ViewModel.RegisterViewModel
@{
    Layout = "../Shared/_Layout.cshtml";
}

<!DOCTYPE html>

<html>
<head>
    <title>RequiredDemo</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.EditorForModel("Register")
            <br />
            <input type="submit" value="Submit" />
            <input type="reset" value="Reset" />
        }
    </div>
</body>
</html>
    

We have a simple View. We have used EditorForModel helper to render controls for the Model properties. We have used BeginForm helper to render a form. We have Submit and Reset button for the form.

Controller
[HttpPost]
        public ActionResult RequiredDemo(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                return View();
            }
            else
            {
                return View(model);
            }
        }
    

The form is posted to above action method on submit. In the above method, we have accepted model object as parameter which triggers the model binding and result of model binding is ModelState. When the ModelState is invalid, the model object is returned with the View.

Till now we have seen how to implement the validation Server side. Lets see how to do it client side.

In order to make it work client side we need to make sure following below points.

1. Make sure below two keys are set to true in web.config.


Make sure the keys ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are set to true in the Web.config file.

2. Do not forget to refer below javascript files in your View or in Layout if View refers Layout.


Once you made sure you followed above two points, the validation will happen on client side on form submission. If the form validation is success then form is posted to the server else error message is shown to user.





Remote Validation when JavaScript is disabled on browser.

  • In this article we are going to see what to do when JavaScript is disabled on client browser and Remote attribute does not validate the logic.
  • To understand this article better read Remote Validation article first, we have used same UserName validation scenario in this article.
Remote Validation

What’s wrong when JavaScript is disabled?
When JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code.

Why JavaScript disabled?
It depends on user to user whether they want JavaScript enable on browser or not. Following are the most common reason to disable JavaScript on browser.

Speed & Bandwidth
Usability & Accessibility
Platform Support
Security

Why Server side logic?
The server side logic is necessary as client side logic does not work due to any reason it is always safe and good to have server side logic.



Controller:
 
[HttpPost]
        public ActionResult Index(UserViewModel model)
        {
            RemoteValidationService service = new RemoteValidationService();
            if (service.IsValidUserName(model.UserName))
            {
                ModelState.AddModelError("UserName", "Username already exist");
                return View(model);
            }
            service.SaveUser(model);
            return View();
        }
    
The form is posted to the above Action method. In this method we are checking if username is present in database or not. If username is present in database then we are adding an error to ModelState making it invalid and returning the View with model having model error. So, this will show error message against the UserName control.

Screenshot:



So it is good practice to have server side validation as backup to client side validation. This is how you can cover up the validation performed by Remote attribute by writing server side logic as well.

Editor Templates Example in ASP.NET MVC

Editor Templates Example in ASP.NET  MVC
  • We commonly use HTML helpers and model binding while working with MVC Razor.
  • MVC framework smartly renders HTML for different type of data like textbox for string or int and checkbox for bool proeprty, when EditorFor or EditorForModel helper is used to render the control.
  • We often have requirement where we want something more like rendering dropdown for model's property of type enum.
  • This is where editor template comes to rescue the situation.
  • In this example, we will render a dropdown control for enum type model property.
ViewModel:
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.ComponentModel.DataAnnotations;

        namespace BindingDropdownToEnum.Models
        {
            public class DropdownModel
            {
                [UIHint("DropDownList")]
                public players playerList { get; set; }
            }

            public enum players
            {
                Fabregas = 1,
                Rocisky = 2,
                Ozil = 3,
                Cazorla = 4
            }
        }
    

In the above view model we have created an enum named players. We have created one  class which has one poperty of type players (i.e. enum). We have used DataAnnotation attribute UIHint to indicate MVC framework the editor template to pick while rendering control for the property. In the above example, we are asking MVC framework to use DropDownList cshtml file under Editor Template folder.

View:
    @model BindingDropdownToEnum.Models.DropdownModel

    @{
        ViewBag.Title = "DropdownBinding";
    }

    <h2>DropdownBinding</h2>

    @Html.EditorForModel()

We have used EditorForModel to render controls for model properties.

EditorTemplate:

    @using BindingDropdownToEnum.Models

    @Html.DropDownList("playerList", Enum.GetValues(typeof(players)).Cast<players>().Select(c => new SelectListItem { Text = c.ToString(), Value = c.ToString() }))

In the above EditorTemplate we have rendered a dropdownlist control using the enum. When the view is rendered, the UIHint attribute indicates MVC framework to use EditorTemplate to render the control.
                                       The editor templates are created under EditorTemplates folder which is under Shared folder. Thus using EditorTemplates we can render any control for any type of property using EditorForModel or EditorFor HTML helper.

Screenshots:



The above textbox is rendered when UIHint attribute is not used. The below screenshot shows the result with using UIHint attribute.



Conclusion:



  • Thus the editor templates can be used with EditorFor or EditorForModel helpers.
  • The editor templates can be used to render any type of control for model property.

Upload multiple files to database using ASP.NET MVC

Upload multiple files to database using ASP.NET MVC
  • In this article we will see how to upload multiple files to database. 
  • The main trick is to select multiple files and post it to the controller's action method.
  • The saving code will be same, but will iterate for each file.
Demo

Database:


We have a simple table named UploadedFiles. We have three columns in the table:


  • FileId - This is primary key identity column.
  • ContentType - This column stores the file type.
  • ImageBytes - This column is of type varbinary and stores file bytes.

ViewModel:

       using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;

        namespace FileUpload.ViewModel
        {
            public class FileUploadViewModel
            {
                public IEnumerable<HttpPostedFileBase> File { get; set; }
            }
        }
    
We have created a IEnumerable property of type HttpPostedFileBase to support multiple uploads. The HttpPostedFileBase type property contains file stream and file information when posted to the controller action.

View:



    @model FileUpload.ViewModel.FileUploadViewModel

@{
    ViewBag.Title = "FileUpload";
}

<h2>FileUpload</h2>



    <div>
        @using (Html.BeginForm("UploadMultipleFiles", "FileUpload", FormMethod.Post, new { @enctype = "multipart/form-data" }))
        {
            @Html.TextBoxFor(c => c.File, new { type = "file", multiple = "true" })
            <input type="submit" style="margin-left:40px;cursor:pointer;" id="upload" value="Upload"/>
        }
    </div>

We have referred the above View model in the view. We have used TextBoxFor helper to render file control using model binding. We have used htmlAttribute object to set multiple property of control to true which allows to select multiple files.
            We have created a form using BeginForm helper. We have also created a submit button. When form is submitted the files are posted to UploadMultipleFiles action method of FileUpload controller

Controller:

       [HttpPost]
        public ActionResult UploadMultipleFiles(FileUploadViewModel fileModel)
        {
            FileUploadService service = new FileUploadService();
            foreach (var item in fileModel.File)
            {
                service.SaveFileDetails(item);
            }
            return View("FileUpload");
        }
    
We have accepted the object of our View model as a parameter. This object has the posted files. The File property of the FileUploadViewModel class is iterated for multiple files and each file is saved to database using SaveFileDetails method.

Service:
       public class FileUploadService
    {
        public void SaveFileDetails(HttpPostedFileBase file)
        {
            UploadedFiles newFile = new UploadedFiles();
            newFile.ContentType = file.ContentType;
            newFile.ImageBytes = ConvertToBytes(file);
            using (FileUploadEntities dataContext = new FileUploadEntities())
            {
                dataContext.UploadedFiles.AddObject(newFile);
                dataContext.SaveChanges();
            }
        }

        public byte[] ConvertToBytes(HttpPostedFileBase file)
        {
            byte[] imageBytes = null;
            BinaryReader reader = new BinaryReader(file.InputStream);
            imageBytes = reader.ReadBytes((int)file.ContentLength);
            return imageBytes;
        }
    }
    
The SaveFileDetails saves the file data to the database. The ConvertToBytes method converts the stream to file bytes.

Conclusion:



  • We need to set the multiple attribute to true of the file control.
  • The view model's property should of type IEnumerable.
  • Iterate on the posted files and save it to the database.


Screenshots:





Ways to call Stored procedure using Entity Framework in ASP.NET MVC3 Razor

Ways to call Stored procedure using Entity Framework in ASP.NET  MVC3 Razor
  • In this article we are concentrating on two ways by which we can call stored procedure using entity framework.
  • Entity Framework performs below expectation when fetching large data, so often we use stored procedure to fetch data.
  • In the application where one has used entity framework, one can use entity framework itself to call stored procedure.

Demo

Lets see what are these two ways:

Way 1:
This is probably the simplest method to call a stored procedure with minimal effort.
We have created a simple stored procedure which fetches the registered user to the application. The stored procedure looks like below:
In the above image above is the stored procedure and below is the result that stored procedure returns.

        using (SampleAPPEntities dataContext = new SampleAPPEntities())
            {
                List<Register> userList = dataContext.ExecuteStoreQuery<Register>("RegisteredUsers").ToList();
            }
    

In the above code, we have created a data context object. We have used ExecuteStoreQuery method of data context to fetch the data. The method accepts a parameter which is the name of the stored procedure to call. We are retuning list of type Register class which maps to the Register table in database whose data we are retreiving using stored procedure.


Way 2:
In this method, we first add stored procedure to the .edmx file. The function inport for the stored procedure is created, function import creates a function which uses the stored procedure.

Step 1: Adding stored procedure to EF
Open the edmx file, right click on it, a dialog box will appear as shown below:



Click on Update Model from Database option which will open another dialog box as shown below:

Select the stored procedure and click the Finish button. This will add the stored procedure to the solution or to the edmx file.


In the above image you could see RegisteredUsers added under Stored Procedures folder.

Step 2:
In this step we will see how to add funtion import for the stored procedure.
Right click on the stored procedure added, this will open a window as shown below:
click on the Add Function Import option, this will open another window as shown below:

The function import name field is pre populated, you can give the function name you want, the stored procedure dropdown has the stored procedure for which you want to add function import.
Select the Entities radio button and select the entity to which you want to map the stored procedure. The stored procedure will return the result of the selected entity type. On clicking ok the funtion import will be created for stored procedure.

        using (SampleAPPEntities dataContext = new SampleAPPEntities())
            {
                List<Register> userList1 = dataContext.GetRegisteredUsers().ToList();
            }
    
We can use the funtion import created to call the stored procedure to get the data from Database.
So, these are the two ways by which the stored procedure can be called using entity framework.

Simple Register and Login application in MVC3 Razor with Database interaction

  • In this article we will create a simple project or application which demonstrates how to create simple register and login forms with database interaction.
  • We will use DataAnnotation to validate form input.
  • We will use EDMX and database first approach. In Database first approach, we first create our database and then update the EDMX with the entities.
  • We will create two forms. One for registering for application and other for login into the application.
  • We have divided the article into two parts. The database part shows the database structure and EDMX entities. The code part shows how to create forms and classes and how to save details.

Watch Video


Part 1

Part 2
Part 3
Part 4

Database :

We have created a Database named LoginTp. We have one table in our database to store User's register Details. We have named it as UserDetails. It looks like below :



In the table, UserId is our primary key and is identity(1,1). We are also storing user's firstname, lastname, dob, city, email and password.

We will update our EDMX with this database to create entities.
To see how to update EDMX from DB follow the link :


After updating EDMX or model from Database, our EDMX file looks like below :




The entity is created in the EDMX. We will use this EDMX to interact with the database.

Code :


We have divided the code part based on forms i.e. Register and Login. Lets start with Register Form.


Register :


ViewModel :


We have created a separate folder to hold our ViewModel. We have created a class file named Register.cs which holds properties to render on Register form. The class file looks as below :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Logintp.ViewModel
{
    public class Register
    {
        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
        public DateTime DOB { get; set; }

        [Required]
        public string City { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}

We have defined above properties to render on form. We have also used DataAnnotation attributes to validate the user's input. We have used Required attribute to make all the fields mandatory to answer. We have used DataType attribute to render input type = "password" for pasword property.

View :



@model Logintp.ViewModel.Register
@{
    ViewBag.Title = "Register";
    Layout = "../Shared/_Layout.cshtml";
    }

<h2>Register</h2>

<div style="color:Black;">@Html.ValidationSummary(true)</div>
<div>
@using(Html.BeginForm("SaveRegisterDetails","Register"))
{
@Html.EditorForModel("Register")
<input type="submit" value="Submit" />
}

</div>
@Html.ActionLink("Login","Login")
<script type="text/javascript">
    $(function () {
        $('#DOB').datepicker({
            onSelect: function (date, value) {
                debugger;
                $('#DOB').val(date);
            },
            dateFormat: 'dd/mm/yy'
        });
    });
</script>

We have used EditorForModel helper for rendering controls for properties defined in our Register ViewModel. We have created a button of type submit, which posts our form.
We have also used BeginForm helper to render form. We have passed two parameters, which are action name and controller name. The action specified in the controller will be called on posting the form. We have used jQuery DatePicker for DOB  property. This will render a datepicker on clicking the textbox rendered for DOB property.

Controller :




//This method is the first to call and renders the Register View.
        public ActionResult Register()
        {
            return View();
        }

        //The form's data in Register view is posted to this method. 
        //We have binded the Register View with Register ViewModel, so we can accept object of Register class as parameter.
        //This object contains all the values entered in the form by the user.
        [HttpPost]
        public ActionResult SaveRegisterDetails(Register registerDetails)
        {
            //We check if the model state is valid or not. We have used DataAnnotation attributes.
            //If any form value fails the DataAnnotation validation the model state becomes invalid.
            if (ModelState.IsValid)
            {
                //If the model state is valid i.e. the form values passed the validation then we are storing the User's details in DB.
                RegisterLogin reglog = new RegisterLogin();
                //Calling the SaveDetails method which saves the details.
                reglog.SaveDetails(registerDetails);
                ModelState.AddModelError("", "User Details Saved Successfully");
                return View("Register");
            }
            else
            {
                //If the validation fails, we are returning the model object with errors to the view, which will display the error messages.
                return View("Register",registerDetails);
            }
        }

The Register action method renders the Register View. The user fills the details and post the form. The form is posted to SaveRegisterDetails method. In this method we validates model state. If the model state is valid then the details are saved else user is displayed with error messages.

Service :


In this class we have wrote code to save the details. We have created a folder named Service which will hold the service classes. We have created a class named RegisterLogin. This class contains SaveDetails method. The class file looks like below.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Logintp.ViewModel;
using Logintp.Models;

namespace Logintp.Service
{
    public class RegisterLogin
    {
        //This method accepts object of Register ViewModel class.
        public void SaveDetails(Register register)
        {
            //Creating DataContext object.
            using (LoginTpEntities dataContext = new LoginTpEntities())
            {
                //Creating the UserDetails object which is our entity.
                UserDetails details = new UserDetails();
                details.FirstName = register.FirstName;
                details.LastName = register.LastName;
                details.UserName = register.Email;
                details.Password = register.Password;
                details.City = register.City;
                details.DOB = Convert.ToDateTime(register.DOB);
                //Saving the details.
                dataContext.UserDetails.AddObject(details);
                dataContext.SaveChanges();
            }
        }
    }
}

The service class contains the method or code to save the user details. This we can consider the DataAccess layer as well.
Till this point we have saved the user details. We are done with Register Form. We will see Login form below.


Login :

ViewModel :

public class LoginViewModel
    {
        [Required]
        public string Username { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }

We have created a ViewModel for Login form. We have include two properties.

View :



@model Logintp.ViewModel.LoginViewModel
@{
    ViewBag.Title = "Login";
    Layout = "../Shared/_Layout.cshtml";
}

<h2>Login</h2>

<div style="color:Black;">@Html.ValidationSummary(true)</div>
<div>
@using(Html.BeginForm())
{
@Html.EditorForModel("LoginViewModel")
<input type="submit" value="Login" />
}

</div>

We have used EditorForModel helper again to render controls for the properties in LoginViewmodel. We are posting the form on click of login button.

Controller :

     //This action method renders the Login View.
        public ActionResult Login()
        {
            return View();
        }

        //The login form is posted to this method.
        [HttpPost]
        public ActionResult Login(LoginViewModel model)
        {
            //Checking the state of model passed as parameter.
            if (ModelState.IsValid)
            {
                RegisterLogin login = new RegisterLogin();
                //Validating the user, whether the user is valid or not.
                bool isValidUser = login.IsValidUser(model);
                //If user is valid we are redirecting it to Welcome page.
                if (isValidUser)
                    return View("Welcome");
                else
                {
                    //If the username and password combination is not present in DB then error message is shown.
                    ModelState.AddModelError("Failure", "Wrong Username and password combination !");
                    return View();
                }
            }
            else
            {
                //If model state is not valid, the model with error message is returned to the View.
                return View(model);
            }
        }

        public ActionResult Welcome()
        {
            return View();
        }

The first action method renders the Login form. The login form on submit is posted to the Login Action method. In this method we check the user with username and password combination entered on the login form in DB. If the match is found then user is redircted to Welcome page else error message is shown.

Service :



public bool IsValidUser(LoginViewModel model)
        {
            using (LoginTpEntities dataContext = new LoginTpEntities())
            {
                //Retireving the user details from DB based on username and password enetered by user.
                UserDetails user = dataContext.UserDetails.Where(query => query.UserName.Equals(model.Username) && query.Password.Equals(model.Password)).SingleOrDefault();
                //If user is present, then true is returned.
                if (user == null)
                    return false;
                    //If user is not present false is returned.
                else
                    return true;
            }
        }

The above method validates the presence of username and password combination in database and returns bool value accordingly.

Layout :



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-1.8.3.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.widget.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
</head>

<body>
    @RenderBody()
</body>
</html>

The above is the Layout used. We have added jQuery references for above files to work with jQuery DatePicker.

Snapshots :


Register Form :




Register Form With errors :


Login Form :


Login Form with unmatched Username and Password :




Database Details :




Must Read:

Validate Form using Data Annotation

Sample Register Form in Asp.net MVC3 Razor

Sample Register Form in Asp.net MVC3 Razor

For creating Sample Register Form we have used one controller, two views and one model class.


Watch Video


Following are the Steps :

Step 1 :

Create a new empty internet ASP.NET MVC3 project.

Step 2 :


Creating Controller - Right Click Controller Folder => Add => Controller, a window will open as shown below.




                       


Name the controller as LoginController and choose template as Empty. Click on Add. This will create a LoginController with default Index Action Method as shown below.






Step 3 :
Creating Model - Create a new Model class for our login View.
Right click on Model Folder => Add => New Item. A window opens.        Add a new class file, under Web section and name it as Login.cs as shown below.



After clicking on Add, it will generate a default class file named Login.cs as shown below.



Our Model class is ready. We have to add properties which we are going to use in the Login Form. Add few properties to Login.cs file as shown below.



Our Model class is ready to use. Now we will create a view for Registering.


Step 4 :

Open the LoginController.cs right click inside the Login Method and click on Add View as shown below.



After clicking on Add view, a window will open.


Create a Login View. Do not select any checkboxes. We will create a plain simple view without model and Layout.
If we want we can include the layout and model class later. After creating the view, it will look like below.




Create a form and create controls or markup to display the properties defines in the model.
Include the reference of the model which we created earlier at the top section of the view as shown below.



Points To Remember :

LabelFor - LabelFor allows binding with the model property.
EditorFor - EditorFor renders control depending upon the property. Instead of using editor for, we have other options as well. We can use textbox, dropdown etc.
Form - We gave two attributes to the form. First property is the name of the action method to post the form. The second attribute is the name of the controller.                               button - Submit button is of type submit, on click of this button the form with entire properties is posted to the action method.
        

Lets see how SubmitLoginDetails() action method in controller looks like :



We created an action method of the same name we gave in the Login View's Form. This action method accepts an model object.
When you fill all the fields and press the submit button. The form is posted to this method, and the model object is filled with the values you entered, stored in the model properties. This model object is then passed to View corresponding to the SampleLoginView() action method.


Lets see how SampleLoginView looks like :



This ends our sample login form. This form is simplest of the form without validation.
Before running the application make sure you make changes in the global.asax file, as shown below.




In the Global.asax file, you specify the name of the controller and action method to call, when application runs.
In our case we gave Login as name for controller and Action method.


Flow After Running Application



When you run the application, the debugger hits the Login action method in Login controller as set in the Global.asax file.
In the action method we create an object of the Model class, and pass the object to the view. View renders as following on the browser.

                        

Fill in the details in the form. Suppose we fill the values as below.



                         


After filling the form click on the submit button. It will post the form to the SubmitLoginDetails Action method.


We have passed the model object to the action method. We get all the values we filled in the form, in this object.
This is because, we have binded the form fields with the model properties. This object with form values is passed to the
SubmitLoginDetailsView to display the information.

                                          





The Sample Register Form Tutorial Ends Here !

Must Read :

Simple Register and Login application in MVC3 Razor with Database interaction