marcelo presto

marcelo presto

  • NA
  • 7
  • 1.3k

Data Annotation: Can't see error message in Required Attrib.

Oct 15 2017 10:49 PM
Hello!
 
I'm newbie in ASP.NET and i'm trying to use Data Annotations, but it's not working properly. The problem is when I try to submit a form without fill all Required fields I don't see the error message. The ModelState "if" in the controller seems to work fine because I only see the Content "Working properly!" if I fill both textbox. I want to see the error message. How do I do that?
The Model:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace Test.Marcelo.Models  
  8. {  
  9.     public class User  
  10.     {  
  11.         [Required(ErrorMessage ="Name is mandatory.")]  
  12.         public string Name { get; set; }  
  13.   
  14.         [Required(ErrorMessage ="Last Name is mandatory.")]  
  15.         public string LastName { get; set; }  
  16.     }  

 Controller:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.ComponentModel.DataAnnotations;  
  7. using Test.Marcelo.Models;  
  8.   
  9. namespace Test.Marcelo.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         // GET: Home  
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.   
  19.         public ActionResult UserForm()  
  20.         {  
  21.             return View();  
  22.         }  
  23.   
  24.         [HttpPost]  
  25.         public ActionResult Record(User usr)  
  26.         {  
  27.             if (ModelState.IsValid)  
  28.             {  
  29.                 return Content("Working properly!");  
  30.             }  
  31.             return RedirectToAction("Index");  
  32.         }  
  33.     }  

 The View:
  1. @model Test.Marcelo.Models.User  
  2.   
  3. @{  
  4.     ViewBag.Title = "UserForm";  
  5. }  
  6.   
  7. <!DOCTYPE html>  
  8. <html>  
  9.     <head>  
  10.     </head>  
  11.     <body>  
  12.         @using (Html.BeginForm("Record""Home"))  
  13.         {  
  14.             @Html.LabelFor(m => m.Name)  
  15.             @Html.TextBoxFor(m => m.Name)  
  16.             @Html.ValidationMessageFor(m => m.Name)<br />  
  17.   
  18.             @Html.LabelFor(m => m.LastName)  
  19.             @Html.TextBoxFor(m => m.LastName)  
  20.             @Html.ValidationMessageFor(m => m.LastName)<br />  
  21.   
  22.             <input type="submit" value="Record" />  
  23.         }  
  24.     </body>  
  25. </html> 
 

Answers (4)