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();
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@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>
<div class="row">
<div class="col-md-4">
<form asp-action="Index">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Age" class="control-label"></label>
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-default" />
</div>
</form>
@if (ViewData.ModelState.IsValid)
{
<span>Name:</span> @ViewBag.Name;
<br />
<span>Age:</span> @ViewBag.Age;
}
</div>
</div>
</body>
</html>
Screenshot