Amazon Ad

Thursday 8 August 2013

MVC 4 Form Validations With LINQ



Hi Guys,

Today i am going to tell you how to add validations on

a MVC form when LINQ is used.

The idea is to use MetadataType attribute and create a

partial class with the same name used in the LINQ

generated class.


Step 1. Create a table in the MS Sql database, with name Employee. Add columns
a. EmpId
b. EmpCode
c. EmpName

Step 2. Create Linq to Sql classes for the database with project name FirstAppDll.

Step 3. Create a model class for the employee

    [MetadataType(typeof(FirstAppDll.Employee))]
    public partial class Employee
    {
        [Required]
        public int EmpId { get; set; }

        [Required(ErrorMessage="Please Enter Employee Code")]
        [Range(3,12,ErrorMessage="Please Enter Employee Code Between 3 to 12 Characters")]
        public string EmpCode { get; set; }

        [Required(ErrorMessage="Please Enter Employee Name")]
        [StringLength(50,ErrorMessage="Employee Name Can Be Less Than 50 Characters")]
        public string EmpName { get; set; }
    }

Step 4. Your controller class should look like

// GET:/Employee/Create (For Blank Create Form)
        public ActionResult Create()
        {
            Employee emp = new Employee();
            return View(emp);
        }

        // POST:/Employee/Create (For saving the saved object from the form into the object)
        [HttpPost]
        public ActionResult Create(Employee obj)
        {
            if (ModelState.IsValid)
            {
                using (FirstAppDll.EmployeeLibraryDataContext context = new FirstAppDll.EmployeeLibraryDataContext())
                {
                    FirstAppDll.Employee emp = new FirstAppDll.Employee();
                    emp.EmpCode = obj.EmpCode;
                    emp.EmpName = obj.EmpName;
                    context.Employees.InsertOnSubmit(emp);
                    context.SubmitChanges();
                    return Redirect("/Employee/Create");
                }
            }
            return View(obj);
        }

Step 5. Generate the view by using the scaffolding for the partial class created. Generate the "Create" scaffold for the class Employee in the mvc project.


That's it folks, Check the form by typing localhost:yourport/Employee/Create and the validations are ready for you.

Thanks
Ritesh

No comments:

Post a Comment

Comments are welcome, Please join me on my Linked In account

http://in.linkedin.com/pub/ritesh-tandon/21/644/33b

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...