Introduction
I am a beginner in MVC. I don't have knowledge regarding MVC but I am keen to learn this new framework. In this article, we will create a form in MVC and wilI add validation through the use of Data Annotations. Thus, let's start.
Description
Create a new Web project and add MVC Web template without authentication. You will see some already build in controller and view in the Application. If you run the Application, you will see the Web Pages of Home, About, Contact etc. in the application. We are here to implement validation, using Data Annotations, which we can implement on any model, so our first requirement is to create a model in which we declare all the properties we require in our form. Right click on Model and add new class with the name clsMembers or anything you want, according to your need and add properties you want in this.Take a look on the code, given below, for the properties I made in the Members class.
clsMembers.cs
You can see in the image, shown above, I created a class in the Model folder and declared the properties in it. You will see above each property I have defined or called; some properties like Required, StringLenght, DataType etc. All these are the attributes from the class Data Annotations.
You will add the attribute you want above each property, according to your need. For example, I want all these fields as required, so I write the attribute [
Required(ErrorMessage="")] and then the error message I want to show with the property. This is what you have to do with all the properties and you can add other attributes. For example, you can see on the email password, and we have other attribute also. You can Google about these attributes or can even search here on C Sharp Corner. Thus, our first step is done.
Now, we will create a Controller and will add a view from the controller.
Add a controller with the name Account and create an Action Result with the name Register like the code, given below:
- public class AccountController : Controller
- {
-
- public ActionResult Register()
- {
- return View();
- }
- }
Now, right click on the ActionResult Register and add view with the same name. After adding view, it's time to create the form.
- @model MVCDemo.Models.clsMembers
- @{
- ViewBag.Title = "Register";
- }
- <style type="text/css">
- .field-validation-error {
- color: #ff0000;
- }
-
- .field-validation-valid {
- display: none;
- }
-
- .input-validation-error {
- border: 1px solid #ff0000;
- background-color: #ffeeee;
- }
- </style>
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery.validate.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
- <h2>Register</h2>
- <div style="margin:auto;width:50%;">
- @using (@Html.BeginForm("Register", "Account", FormMethod.Post, new { id = "frmRegister" }))
- {
- <table>
- <tr>
- <td>
- @Html.Label("Firstname")
- </td>
- <td>
- @Html.TextBoxFor(m => m.FirstName, new { placeholder = "Firstname" })
- </td>
- <td>
- @Html.ValidationMessageFor(m => m.FirstName)
- </td>
- </tr>
- <tr>
- <td>
- @Html.Label("Lastname")
- </td>
- <td>
- @Html.TextBoxFor(m => m.LastName, new { placeholder = "Lastname" })
- </td>
- <td>
- @Html.ValidationMessageFor(m => m.LastName)
- </td>
- </tr>
- <tr>
- <td>
- @Html.Label("Department")
- </td>
- <td>
- @Html.TextBoxFor(m => m.Department, new { placeholder = "Department" })
- </td>
- <td>
- @Html.ValidationMessageFor(m => m.Department)
- </td>
- </tr>
- <tr>
- <td>
- @Html.Label("Username")
- </td>
- <td>
- @Html.TextBoxFor(m => m.Username, new { placeholder = "Username" })
- </td>
- <td>
- @Html.ValidationMessageFor(m => m.Username)
- </td>
- </tr>
- <tr>
- <td>
- @Html.Label("Password")
- </td>
- <td>
- @Html.TextBoxFor(m => m.Password, new { type = "password", placeholder = "Password" })
- </td>
- <td>
- @Html.ValidationMessageFor(m => m.Password)
- </td>
- </tr>
- <tr>
- <td>
- @Html.Label("ConfirmPassword")
- </td>
- <td>
- @Html.TextBoxFor(m => m.ConfirmPassword, new { type = "password", placeholder = "ConfirmPassword" })
- </td>
- <td>
- @Html.ValidationMessageFor(m => m.ConfirmPassword)
- </td>
- </tr>
- <tr>
- <td>
- @Html.Label("Email")
- </td>
- <td>
- @Html.TextBoxFor(m => m.Email, new { placeholder = "Email Address" })
- </td>
- <td>
- @Html.ValidationMessageFor(m => m.Email)
- </td>
- </tr>
- <tr>
- <td></td>
- <td style="text-align:center;">
- <input type="submit" value="Submit" />
- </td>
- <td></td>
- </tr>
- </table>
- }
- </div>
In the view (Register), we will create the form now. In the code, given above, check the first line in which we get the reference of Member class so that we can access to the properties of the class. Afterwards, we create the form, using HTML Helper class. Thus, everything is done for now. We just need JavaScript file to run the validation on submit click, if we want to validate this on the client side.
You can see the code, given above. We give the reference of three JavaScript files in the page. They will work with the Data Annotations, if you don't give the reference of these files, your validation will not work (Client Side). Hence, we will add the reference and then everything is done. Now, it's time to run the code, just hit F5 to see the output and you will see the output, as shown below:
If you hit the submit button, you will get the validation message, as shown in the image, given above. This is a client side validation, using Data Annotations. Now, lets do the
Server side validation with Data Annotations. Comment on the Script files on the register page.
Now, if you see in the code, given above, where we are creating forms with the help of HTML Helper class, we write the action name and the controller name, where this action exists and the method type.
Thus, now we already having a Registered Action in the Account Controller and here we are again giving the action with the same name -- then what will happen? We will create an action result type of Post with the name Register, it will pass the model in it and will chec if the model state is valid or not.
- [HttpPost]
- public ActionResult Register(clsMembers objMembers)
- {
- if (ModelState.IsValid)
- {
- return View("Completed");
- }
- else
- {
- return View();
- }
- }
If you see in the code given above, we created an action with the name Register and passed the Model in it. Afterwards, wewill check if the Model State is valid or not; if it's valid, then we can save the data in the database( I haven't written code for it), or if not, then empty view will return and it will automatically invoke the Data Annotations validation. Our Server side validation is done. If you still run the code, hit on Submit and make a breakpoint out here on action. You will clearly understand the validation is running from the Server side.
That's it for now. Hope this will be helpful for newcomers in MVC like me.