Reputation: 10779
I am trying to raise validation error in an ASP.Net MVC 3 application.
When the user enters a number that is greater than 1000 an error message should be displayed. with the following code on a view model it doesn't seem to be working.
What do i need to change?
[Range(0, 1000, ErrorMessage = "Total number of rows to display must be between 0 to 1000")]
public int DisplayTop { get; set; }
cshtml :
@model Calc.Models.CountingVM
@{
ViewBag.Title = "Reports";
Layout = "~/Views/Shared/_reportsLayout.cshtml";
}
@using (Html.BeginForm("Reports", "Calc", FormMethod.Post, new { @id = "frmReport" }))
{
.........
@Html.TextBoxFor(c => c.DisplayTop, "1000")
@Html.ValidationMessageFor(c => c.DisplayTop)
}
Action Method :
public ActionResult Reports(string ReportName, CalcCriteria criteria)
{
if ((criteria == null) || (criteria.nId == null))
{
criteria = TempData["criteria"] as CalcCriteria;
TempData["criteria"] = criteria; // For reload, without this reloading the page causes null criteria.
}
ReportType c = (ReportType)Enum.Parse(typeof(ReportType), ReportName, true);
JavaScriptSerializer serializer = new JavaScriptSerializer();
string vmJson = string.Empty;
switch (c)
{
.....
int displayTop;
..........
case ReportType.Inventory_Counts_Report:
..............
displayTop = Convert.ToInt32(Request["DisplayTop"]);
........
return View("Counting", CountingVM);
default:
return View();
}
return View(); }
Thanks
BB
Upvotes: 0
Views: 1089
Reputation: 5482
Try
@Html.EditorFor(c => c.DisplayTop, "1000")
I guess, that the problem occures, becase your property is of type int, and the range is for type int, byt you are showing it in a textbox.
Also you need to add ModelState.IsValid
in your controller. For example:
[HttpPost]
public ActionResult Create(YourModel model)
{
if(ModelState.IsValid)
{
// Put your logic here
}
return View(create)
}
Upvotes: 0
Reputation: 38468
You also need to display the validation message:
@Html.ValidationMessageFor(c => c.DisplayTop)
Upvotes: 1