Reputation: 31
//Index Page (view) /Employee/Index
@model DataAnotaionExample.Models.Employee
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="./Add">
Enter [email protected](m=>Model.Name)
@Html.ValidationMessageFor(m=>Model.Name)
<input type="submit" value="Submit" />
</form>
//Employee Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DataAnotaionExample.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index()
{
return View();
}enter code here
}
}
Model Class Employee.cs
namespace DataAnotaionExample.Models
{
public class Employee
{
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}
This is my code, If I keep the Name field blank then it will not throw the error like the field is required.
This Code Created in Asp.Net MVC5 Framework
Upvotes: 1
Views: 285
Reputation: 140
First you have add razor like this
@model DataAnotaionExample.Models.Employee
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="./Add">
//this one
@Html.ValidationSummary(true)
Enter [email protected](m=>Model.Name)
@Html.ValidationMessageFor(m=>Model.Name)
<input type="submit" value="Submit" />
</form>
Then you should like validation script like this in your "_Layout.cshtml" page
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
Or you can use this script in your App_Start->BundleConfig
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js"
));
I hope this code is useful for you.
Upvotes: 0
Reputation: 114
make sure you have added
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script
at the end of your layout page:
Upvotes: 1