Hi rani,
Check this example. Now please take its reference and correct your code.
Model
public class PersonModel
{
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
[Required(ErrorMessage = "Age is required.")]
[Range(18, 60, ErrorMessage = "Enter Age between 18 and 60.")]
public int? Age { get; set; }
}
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
if (ModelState.IsValid)
{
ViewBag.Name = person.Name;
ViewBag.Age = person.Age;
}
return View();
}
}
@model TextBox_Validation_Core_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="container">
<div class="col-md-4">
<form asp-action="Index">
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "control-label" })
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Age, new { @class = "control-label" })
@Html.TextBoxFor(m => m.Age, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Age, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-default" />
</div>
</form>
<hr />
@if (ViewData.ModelState.IsValid)
{
<span>Name:</span> @ViewBag.Name;
<br />
<span>Age:</span> @ViewBag.Age;
}
</div>
</div>
}
</body>
</html>
Screenshot