Server Side Validation In MVC using ModelState

Server Side Validation In MVC using ModelState

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace ServerSideValidationInMVC.Models
{
    public class Student
    {
        [Required(ErrorMessage = "Name is Requirde")]
        public string Name { get; set; }
        [Required(ErrorMessage = "Email is Requirde")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                            ErrorMessage = "Email is not valid")]
        public string Email { get; set; }
    }
}



@model ServerSideValidationInMVC.Models.Student
@{
    ViewBag.Title = "Index";
}
@if (ViewData.ModelState.IsValid)
{
    if (@ViewBag.Name != null)
    {
        <b>
            Name : @ViewBag.Name<br />
            Email : @ViewBag.Email
        </b>
    }
}
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Student</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}


using ServerSideValidationInMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ServerSideValidationInMVC.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
       [AcceptVerbs(HttpVerbs.Post)]
       // [HttpPost]
        public ActionResult Index(Student model)
        {
            if (ModelState.IsValid)
            {
                ViewBag.Name = model.Name;
                ViewBag.Email = model.Email;
            }
            return View(model);
        }
}
}

Comments

Popular posts from this blog

Kendo Control(Dynamics)

Override Authorize Filters in MVC

Form Validation