Model Binding in ASP.NET MVC

MVC

There are the following three ways to pass a value or data from a view to an action:

  • Parameterized Query.
  • Form Data.
  • Model Binding.

Model binding: In this method we can bind a form using a Model class. The class is bound with the form, in other words the User Interface (View). So the form can be validated using the class and the control's value like the value from TextBoxes and others are passed to the Action Method directly.

  • What we will do in this application.
  • We learn how to do Model Binding in MVC.
  • We will create a User Registration Form.
  • We will perform Login Authentication.
  • We will Validate the Form using Model Binding.
  • For all these operations we will use the Entity Framework.

    (The database script is available in the file.)
Create the following table inside your database:
  1. create table tbl_Student_LogIn
  2. (
  3. ID int identity primary key,
  4. Student_Name varchar(50),
  5. UserName varchar(50),
  6. Password varchar(50),
  7. RePassword varchar(50)
  8. )

Step 1

Add a Controller to the Project as in the following:

controller

Add Controller

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace MvcApplication3.Controllers
  7. {
  8. public class Student_ManagementController : Controller
  9. {
  10. //
  11. // GET: /Student_Management/
  12. public ActionResult Index()
  13. {
  14. return View();
  15. }
  16. }
  17. }

Step 2

Add a class to the Model folder by right-clicking it then selecting Add Class.

add class

Step 3

Provide it a name such as Cls_Student_LogIn.

class

Class Name Added: "Cls_Student_LogIn"

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. //
  6. using System.Data.Entity;
  7. using System.ComponentModel.DataAnnotations;
  8. namespace MvcApplication3.Models
  9. {
  10. public class Cls_Student_LogIn
  11. {
  12. }
  13. }

Step 4

Add properties to the class for the database table's columns.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. //
  6. using System.Data.Entity;
  7. using System.ComponentModel.DataAnnotations;
  8. namespace MvcApplication3.Models
  9. {
  10. public class Cls_Student_LogIn
  11. {
  12. public string PStudent_Name
  13. {
  14. set;
  15. get;
  16. }
  17. public string PUser_Name
  18. {
  19. set;
  20. get;
  21. }
  22. public string PPassword
  23. {
  24. set;
  25. get;
  26. }
  27. public string PRepassword
  28. {
  29. set;
  30. get;
  31. }
  32. }
  33. }

Step 5

Add a view (to the Controller by right-clicking).

Add a View

Step 6

Go to View.

Go To View

Step 7

At the Index View do this.

Index View

Index script and code:

  1. @model MvcApplication3.Models.Cls_Student_LogIn
  2. @{
  3. ViewBag.Title = "Index";
  4. }
  5. <h6>Index Page Of Student Management System</h6>
  6. @using (Html.BeginForm("LogIn","Student_Management",FormMethod.Post))
  7. {
  8. <table>
  9. <tr>
  10. <td>User Name</td><td>:</td><td>*</td><td>@Html.TextBoxFor(Model=>Model.PUser_Name)</td>
  11. </tr>
  12. <tr>
  13. <td>Password</td><td>:</td><td>*</td><td>@Html.PasswordFor(Model=>Model.PPassword)</td>
  14. </tr>
  15. <tr>
  16. <td>Log In</td><td>:</td><td></td><td><input type="submit" value="Log In" /></td>
  17. </tr>
  18. <tr>
  19. <td>Don't Have An Account</td><td>:</td><td></td><td>@Html.ActionLink("New User", "NewUser","Student_Management")</td>
  20. </tr>
  21. </table>
  22. }

Run the application and watch the output:

index

Note: When we click on the Submit Button it automatically finds the Login Action Method. So we need to add an Action Method named as Login.

But before that let's validate the Form

Step 8

Add the following two namespaces to the “Cls_Student_LogIn.cs” class if not yet added.

  • using System.Data.Entity;
  • using System.ComponentModel.DataAnnotations;

Property: We must add basically these three properties to the class.

  • [Required(ErrorMessage = " ")]
  • [DataType(DataType.Text)]
  • [Display(Name = " ")]

Step 9

Add validation code to the class or modify the class “Cls_Student_LogIn.cs”.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. //
  6. using System.Data.Entity;
  7. using System.ComponentModel.DataAnnotations;
  8. namespace MvcApplication3.Models
  9. {
  10. public class Cls_Student_LogIn
  11. {
  12. [Required(ErrorMessage = "Enter Your Name")]
  13. [DataType(DataType.Text)]
  14. [Display(Name = "Name")]
  15. public string PStudent_Name
  16. {
  17. set;
  18. get;
  19. }
  20. [Required(ErrorMessage = "Enter Your User Name")]
  21. [DataType(DataType.Text)]
  22. [Display(Name = "User Name")]
  23. public string PUser_Name
  24. {
  25. set;
  26. get;
  27. }
  28. [Required(ErrorMessage = "Enter Your Password")]
  29. [DataType(DataType.Password)]
  30. [Display(Name = "Password")]
  31. public string PPassword
  32. {
  33. set;
  34. get;
  35. }
  36. [Required(ErrorMessage = "Enter Your RePassword")]
  37. [DataType(DataType.Password)]
  38. [Display(Name = "RePassword")]
  39. public string PRepassword
  40. {
  41. set;
  42. get;
  43. }
  44. }
  45. }

Step 10

Then go to the View files, in this case the Index.cshtml file and 3 jQuery files.

JQuery files

Step 11

After dragging:

  1. <h6>Index Page Of Student Management System</h6>
  2. <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
  3. <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
  4. <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

Step 12

Modify the Index.cshtml file as in the following:

  1. @model MvcApplication3.Models.Cls_Student_LogIn
  2. @{
  3. ViewBag.Title = "Index";
  4. }
  5. <h6>Index Page Of Student Management System</h6>
  6. <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
  7. <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
  8. <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
  9. @using (Html.BeginForm("LogIn","Student_Management",FormMethod.Post))
  10. {
  11. <table>
  12. <tr>
  13. <td>User Name</td><td>:</td><td>*</td><td>@Html.TextBoxFor(Model=>Model.PUser_Name)</td>
  14. </tr>
  15. <tr>
  16. <td></td><td></td><td></td><td>@Html.ValidationMessageFor(Mode=>Model.PUser_Name)</td>
  17. </tr>
  18. <tr>
  19. <td>Password</td><td>:</td><td>*</td><td>@Html.PasswordFor(Model=>Model.PPassword)</td>
  20. </tr>
  21. <tr>
  22. <td></td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PPassword)</td>
  23. </tr>
  24. <tr>
  25. <td>Log In</td><td>:</td><td></td><td><input type="submit" value="Log In" /></td>
  26. </tr>
  27. <tr>
  28. <td>Don't Have An Account</td><td>:</td><td></td><td>@Html.ActionLink("New User", "NewUser","Student_Management")</td>
  29. </tr>
  30. </table>
  31. }

Run the application and test it for validation.

Validation

Step 13

We need to register for a New User and to perform Log on Authentication.

  1. Insert New Data
  2. Log On Program
  3. We need to design the form for Insert and validate it.

Step 14

Add a new Action Method to the “Student_Management” controller.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace MvcApplication3.Controllers
  7. {
  8. public class Student_ManagementController : Controller
  9. {
  10. //
  11. // GET: /Student_Management/
  12. public ActionResult Index()
  13. {
  14. return View();
  15. }
  16. public ActionResult NewUser()
  17. {
  18. return View();
  19. }
  20. }
  21. }

Step 15

Right-click on the NewUser() Action Method and add a new View.

NewUser

NewUser.cshtml file

  1. @{
  2. ViewBag.Title = "NewUser";
  3. }
  4. <h2>NewUser</h2>

Design it ("New User") and validate it as we have done previously.

Step 16

Again do Model Binding.

  1. Bind the class “Cls_Student_LogIn.cs” to it.
  2. Validate it

Design of the NewUser.cshtml file

  1. @model MvcApplication3.Models.Cls_Student_LogIn
  2. @{
  3. ViewBag.Title = "NewUser";
  4. }
  5. <h2>NewUser</h2>
  6. <h4>@Html.ActionLink("Go Back", "Index", "Student_Management")</h4>
  7. <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
  8. <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
  9. <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
  10. @using (@Html.BeginForm("Insert", "Student_Management", FormMethod.Post))
  11. {
  12. <table>
  13. <tr>
  14. <td>Enter Your Name</td><td>:</td><td>*</td><td>@Html.TextBoxFor(Model=>Model.PStudent_Name)</td>
  15. </tr>
  16. <tr>
  17. <td> </td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PStudent_Name)</td>
  18. </tr>
  19. <tr>
  20. <td>Enter Your UserName</td><td>:</td><td>*</td><td>@Html.TextBoxFor(Model=>Model.PUser_Name)</td>
  21. </tr>
  22. <tr>
  23. <td> </td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PUser_Name)</td>
  24. </tr>
  25. <tr>
  26. <td>Enter Password</td><td>:</td><td>*</td><td>@Html.PasswordFor(Model=>Model.PPassword)</td>
  27. </tr>
  28. <tr>
  29. <td> </td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PPassword)</td>
  30. </tr>
  31. <tr>
  32. <td>Enter RePassword</td><td>:</td><td>*</td><td>@Html.PasswordFor(Model=>Model.PRepassword)</td>
  33. </tr>
  34. <tr>
  35. <td> </td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PRepassword)</td>
  36. </tr>
  37. <tr>
  38. <td>Submit The Data </td><td>:</td><td></td><td><input type="submit" value="Save" /></td>
  39. </tr>
  40. </table>
  41. }

Run the application:

Run the Application

Click on the New User link:

New User Link

Now our data validation is complete. We will now do the save operation of the new user.

First create a database table as in the following:

  1. create table tbl_Student_LogIn
  2. (
  3. ID int identity primary key,
  4. Student_Name varchar(50),
  5. UserName varchar(50),
  6. Password varchar(50),
  7. RePassword varchar(50)
  8. )
  9. GO
  10. --
  11. select * from tbl_Student_LogIn

Procedure:

  • Add this table to the EntityFramework file (.Edmx) file.
  • Remember, we have already created a class file for the table “Cls_Student_LogIn”.
  • Right-click on the .edmx file and select Update Model.

    Update Model

Step 1

Add the table name.

Add the Table Name

Step 2

After adding the table, you will see this output. Click Save.

output

Step 3

For saving the New User we will create an ActionMethod Insert and we will insert the data now.

  • Go to the Controller and create an Action Method as Insert.
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. using System.Web.Mvc;
    6. //include the model namespaces here
    7. using MvcApplication3.Models;
    8. namespace MvcApplication3.Controllers
    9. {
    10. public class Student_ManagementController : Controller
    11. {
    12. //
    13. // GET: /Student_Management/
    14. public ActionResult Index()
    15. {
    16. return View();
    17. }
    18. public ActionResult NewUser()
    19. {
    20. return View();
    21. }
    22. public ActionResult Insert()
    23. {
    24. return View();
    25. }
    26. }
    27. }
  • To add a View for It, right-click on Insert() then select Add view.

    add view

    Watch it:

    Watch it

Step 4

Write code for the Insert operation at the Insert() action method in the Controller.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. //include the model namespaces here
  7. using MvcApplication3.Models;
  8. namespace MvcApplication3.Controllers
  9. {
  10. public class Student_ManagementController : Controller
  11. {
  12. //
  13. // GET: /Student_Management/
  14. public ActionResult Index()
  15. {
  16. return View();
  17. }
  18. public ActionResult NewUser()
  19. {
  20. return View();
  21. }
  22. public ActionResult Insert(Cls_Student_LogIn Obj) // put the class name and create an object of it
  23. {
  24. using (MVC_PracticeEntities DbContext = new MVC_PracticeEntities())
  25. {
  26. //table Object
  27. tbl_Student_LogIn tbl = new tbl_Student_LogIn();
  28. //
  29. tbl.Student_Name = Obj.PStudent_Name;
  30. tbl.UserName = Obj.PUser_Name;
  31. tbl.Password = Obj.PPassword;
  32. tbl.RePassword = Obj.PRepassword;
  33. //
  34. DbContext.AddTotbl_Student_LogIn(tbl);
  35. int i = DbContext.SaveChanges();
  36. if (i > 0)
  37. {
  38. ViewBag.M = "One User Created Successfully.";
  39. }
  40. //
  41. }
  42. return View();
  43. }
  44. }
  45. }
  • Run the application and add a user.

    Run application

  • Click on Save:
    Click On Save
  • Add some more users and watch them in the database.
  • SQL Management Studio:
    1. select * from tbl_Student_LogIn
    SQL Management Studio

  • Now we will do the Login authentication.

Step 5

Add a Login() action method to the Controller.

  • Go To The Controller and add an action method named "Login”.
    1. public ActionResult LogIn()
    2. {
    3. return View();
    4. }
  • Add a View. To do that right-click on Login() then selct Add View.

    Add a View for this Login

  • Watch it after was created.

    after is created

  • Now we will do the Login Authentication as in the following:

    • Go The the Controller.
    • Add the following code for Login().
      1. using System;
      2. using System.Collections.Generic;
      3. using System.Linq;
      4. using System.Web;
      5. using System.Web.Mvc;
      6. //include the model namespaces here
      7. using MvcApplication3.Models;
      8. namespace MvcApplication3.Controllers
      9. {
      10. public class Student_ManagementController : Controller
      11. {
      12. //
      13. // GET: /Student_Management/
      14. public ActionResult Index()
      15. {
      16. return View();
      17. }
      18. public ActionResult NewUser()
      19. {
      20. return View();
      21. }
      22. public ActionResult Insert(Cls_Student_LogIn Obj) // put the class name and create an object of it
      23. {
      24. using (MVC_PracticeEntities DbContext = new MVC_PracticeEntities())
      25. {
      26. //table Object
      27. tbl_Student_LogIn tbl = new tbl_Student_LogIn();
      28. //
      29. tbl.Student_Name = Obj.PStudent_Name;
      30. tbl.UserName = Obj.PUser_Name;
      31. tbl.Password = Obj.PPassword;
      32. tbl.RePassword = Obj.PRepassword;
      33. //
      34. DbContext.AddTotbl_Student_LogIn(tbl);
      35. int i = DbContext.SaveChanges();
      36. if (i > 0)
      37. {
      38. ViewBag.M = "One User Created Successfully.";
      39. }
      40. //
      41. }
      42. return View();
      43. }
      44. public ActionResult LogIn(Cls_Student_LogIn Obj)// put the class name and create an object of it
      45. {
      46. using (MVC_PracticeEntities DbContext = new MVC_PracticeEntities())
      47. {
      48. tbl_Student_LogIn tbl = new tbl_Student_LogIn();
      49. var Data2 = (from abc in DbContext.tbl_Student_LogIn
      50. where abc.UserName == Obj.PUser_Name && abc.Password == Obj.PPassword
      51. select abc).SingleOrDefault();
      52. }
      53. ViewBag.M = "Welcome User";
      54. return View();
      55. }
      56. }
      57. }
  • Run the application and watch the output or perform a Login.
    perform a Login

  • Click on Login.

    Login

    I am again providing all the code and scripts.

  • The following is the database table script.
    1. create table tbl_Student_LogIn
    2. (
    3. ID int identity primary key,
    4. Student_Name varchar(50),
    5. UserName varchar(50),
    6. Password varchar(50),
    7. RePassword varchar(50)
    8. )
    9. GO

  • The following is the full code of the Cls_Student_LogIn class (Model Class).
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. //
    6. using System.Data.Entity;
    7. using System.ComponentModel.DataAnnotations;
    8. using System.Web.Mvc;
    9. namespace MvcApplication3.Models
    10. {
    11. public class Cls_Student_LogIn
    12. {
    13. [Required(ErrorMessage = "Enter Your Name")]
    14. [DataType(DataType.Text)]
    15. [Display(Name = "Name")]
    16. public string PStudent_Name
    17. {
    18. set;
    19. get;
    20. }
    21. [Required(ErrorMessage = "Enter Your User Name")]
    22. [DataType(DataType.Text)]
    23. [Display(Name = "User Name")]
    24. public string PUser_Name
    25. {
    26. set;
    27. get;
    28. }
    29. [Required(ErrorMessage = "Enter Your Password")]
    30. [DataType(DataType.Password)]
    31. [Display(Name = "Password")]
    32. public string PPassword
    33. {
    34. set;
    35. get;
    36. }
    37. [Required(ErrorMessage = "Enter Your Re Password")]
    38. [DataType(DataType.Password)]
    39. [Display(Name = "RePassword")]
    40. [Compare("PPassword", ErrorMessage = "The Password and Re Password do not match.")]
    41. public string PRepassword
    42. {
    43. set;
    44. get;
    45. }
    46. }
    47. }

  • The following is the full code of Index.cshtml.
    1. @model MvcApplication3.Models.Cls_Student_LogIn
    2. @{
    3. ViewBag.Title = "Index";
    4. }
    5. <h6>Index Page Of Student Management System</h6>
    6. <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    7. <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
    8. <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
    9. @using (Html.BeginForm("LogIn","Student_Management",FormMethod.Post))
    10. {
    11. <table>
    12. <tr>
    13. <td>User Name</td><td>:</td><td>*</td><td>@Html.TextBoxFor(Model=>Model.PUser_Name)</td>
    14. </tr>
    15. <tr>
    16. <td></td><td></td><td></td><td>@Html.ValidationMessageFor(Mode=>Model.PUser_Name)</td>
    17. </tr>
    18. <tr>
    19. <td>Password</td><td>:</td><td>*</td><td>@Html.PasswordFor(Model=>Model.PPassword)</td>
    20. </tr>
    21. <tr>
    22. <td></td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PPassword)</td>
    23. </tr>
    24. <tr>
    25. <td>Log In</td><td>:</td><td></td><td><input type="submit" value="Log In" /></td>
    26. </tr>
    27. <tr>
    28. <td>Don't Have An Account</td><td>:</td><td></td><td>@Html.ActionLink("New User", "NewUser","Student_Management")</td>
    29. </tr>
    30. </table>
    31. }

  • The following is the full code of NewUser.cshtml.
    1. @model MvcApplication3.Models.Cls_Student_LogIn
    2. @{
    3. ViewBag.Title = "NewUser";
    4. }
    5. <h2>NewUser</h2>
    6. <h4>@Html.ActionLink("Go Back", "Index", "Student_Management")</h4>
    7. <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    8. <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
    9. <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
    10. @using (@Html.BeginForm("Insert", "Student_Management", FormMethod.Post))
    11. {
    12. <table>
    13. <tr>
    14. <td>Enter Your Name</td><td>:</td><td>*</td><td>@Html.TextBoxFor(Model=>Model.PStudent_Name)</td>
    15. </tr>
    16. <tr>
    17. <td> </td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PStudent_Name)</td>
    18. </tr>
    19. <tr>
    20. <td>Enter Your UserName</td><td>:</td><td>*</td><td>@Html.TextBoxFor(Model=>Model.PUser_Name)</td>
    21. </tr>
    22. <tr>
    23. <td> </td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PUser_Name)</td>
    24. </tr>
    25. <tr>
    26. <td>Enter Password</td><td>:</td><td>*</td><td>@Html.PasswordFor(Model=>Model.PPassword)</td>
    27. </tr>
    28. <tr>
    29. <td> </td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PPassword)</td>
    30. </tr>
    31. <tr>
    32. <td>Enter Re Password</td><td>:</td><td>*</td><td>@Html.PasswordFor(Model=>Model.PRepassword)</td>
    33. </tr>
    34. <tr>
    35. <td> </td><td></td><td></td><td>@Html.ValidationMessageFor(Model=>Model.PRepassword)</td>
    36. </tr>
    37. <tr>
    38. <td>Submit The Data </td><td>:</td><td></td><td><input type="submit" value="Save" /></td>
    39. </tr>
    40. </table>
    41. }

  • The following is the full code for the Controller again:
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Web;
    5. using System.Web.Mvc;
    6. //include the model namespaces here
    7. using MvcApplication3.Models;
    8. namespace MvcApplication3.Controllers
    9. {
    10. public class Student_ManagementController : Controller
    11. {
    12. //
    13. // GET: /Student_Management/
    14. public ActionResult Index()
    15. {
    16. return View();
    17. }
    18. public ActionResult NewUser()
    19. {
    20. return View();
    21. }
    22. public ActionResult Insert(Cls_Student_LogIn Obj) // put the class name and create an object of it
    23. {
    24. using (MVC_PracticeEntities DbContext = new MVC_PracticeEntities())
    25. {
    26. //table Object
    27. tbl_Student_LogIn tbl = new tbl_Student_LogIn();
    28. //
    29. tbl.Student_Name = Obj.PStudent_Name;
    30. tbl.UserName = Obj.PUser_Name;
    31. tbl.Password = Obj.PPassword;
    32. tbl.RePassword = Obj.PRepassword;
    33. //
    34. DbContext.AddTotbl_Student_LogIn(tbl);
    35. int i = DbContext.SaveChanges();
    36. if (i > 0)
    37. {
    38. ViewBag.M = "One User Created Successfully.";
    39. }
    40. //
    41. }
    42. return View();
    43. }
    44. public ActionResult LogIn(Cls_Student_LogIn Obj)// put the class name and create an object of it
    45. {
    46. using (MVC_PracticeEntities DbContext = new MVC_PracticeEntities())
    47. {
    48. tbl_Student_LogIn tbl = new tbl_Student_LogIn();
    49. var Data2 = (from abc in DbContext.tbl_Student_LogIn
    50. where abc.UserName == Obj.PUser_Name && abc.Password == Obj.PPassword
    51. select abc).SingleOrDefault();
    52. }
    53. ViewBag.M = "Welcome User";
    54. return View();
    55. }
    56. }
    57. }
Output

new user

index page

student management system