server side validation:
Example:
step 1: create student model class:
public class Student
{
[Required(ErrorMessage = "Name is Required")]
public string name { get; set; }
[Required(ErrorMessage = "Email is Required")]
public string Email { get; set; }
}
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:
@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