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; }
- }
- }
- 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
- {
- // GET: Home
- 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");
- }
- }
- }
- @model Test.Marcelo.Models.User
- @{
- ViewBag.Title = "UserForm";
- }
- @using (Html.BeginForm("Record", "Home"))
- {
- @Html.LabelFor(m => m.Name)
- @Html.TextBoxFor(m => m.Name)
- @Html.ValidationMessageFor(m => m.Name)
- @Html.LabelFor(m => m.LastName)
- @Html.TextBoxFor(m => m.LastName)
- @Html.ValidationMessageFor(m => m.LastName)
- "submit" value="Record" />
- }
-
marcelo prestoPosted Oct 16, 2017, 11:38 AM
Ravi PatelPosted Oct 16, 2017, 12:18 AM
Bryian TanPosted Oct 15, 2017, 11:31 PM
Ramesh PalanivelPosted Oct 15, 2017, 11:20 PM