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:
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:
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Test.App.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; }
}
}
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using Test.App.Models;
namespace Test.App.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");
}
}
}
C#:
@model Test.App.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>