Search This Blog

Tuesday, 21 June 2016

Mvc server side validation

server side validation:

Example:

step 1: create student model class:

public class Student
{
[Required(ErrorMessage = "Name is Required")]
public string name { getset; }
[Required(ErrorMessage = "Email is Required")]
public string Email { getset; }
}

Step 2: Create Student controller:

public class StudentController : Controller
{
public ActionResult Index()
{
return View(); //To create (view) to show message:
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Student model)
{
if (ModelState.IsValid)
{
ViewBag.Name = model.name;
ViewBag.Email = model.Email;
}
return View(model);
}
}


Index.cshtml:

@model ServerValidation.Models.Student


@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>
}  

No comments:

Post a Comment