Thursday 20 August 2015

Add validation error to MVC Controller and display the error in View

Following code would add error to the model based on some logic in the Controller.
In the Controller
    
   if ((leaveSummary.AnnualTaken + numOfDays) > leaveSummary.Annual)
       ModelState.AddModelError("Leave", "Annual Leave exhausted !");
   else
       leaveSummary.AnnualTaken = leaveSummary.AnnualTaken + numOfDays;

AddModelError is the method we are using to add the new error.
To display this view in the model we need to do following in the cshtml
    
        
@if (!ViewData.ModelState.IsValid) { @ViewData.ModelState["Leave"].Errors[0].ErrorMessage }

No comments:

Post a Comment