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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.ComponentModel.DataAnnotations;
-
- namespace Test.Marcelo.Models
- {
- public class User
- {
- [Required(ErrorMessage ="Name is mandatory.")]
- public string Name { get; set; }
-
- [Required(ErrorMessage ="Last Name is mandatory.")]
- public string LastName { get; set; }
- }
- }
Controller:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.ComponentModel.DataAnnotations;
- using Test.Marcelo.Models;
-
- namespace Test.Marcelo.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult UserForm()
- {
- return View();
- }
-
- [HttpPost]
- public ActionResult Record(User usr)
- {
- if (ModelState.IsValid)
- {
- return Content("Working properly!");
- }
- return RedirectToAction("Index");
- }
- }
- }
The View:
- @model Test.Marcelo.Models.User
-
- @{
- ViewBag.Title = "UserForm";
- }
-
- <!DOCTYPE html>
- <html>
- <head>
- </head>
- <body>
- @using (Html.BeginForm("Record", "Home"))
- {
- @Html.LabelFor(m => m.Name)
- @Html.TextBoxFor(m => m.Name)
- @Html.ValidationMessageFor(m => m.Name)<br />
-
- @Html.LabelFor(m => m.LastName)
- @Html.TextBoxFor(m => m.LastName)
- @Html.ValidationMessageFor(m => m.LastName)<br />
-
- <input type="submit" value="Record" />
- }
- </body>
- </html>