**Hi, I'm using .Net 6 & visual studio 2022 community.
My Model validations through Data Annotations are not working into HTMl tags.**
Code:
public class Student
{
public int Id { get; set; }
[Display(Name="Student Name")]
[System.ComponentModel.DataAnnotations.Required(ErrorMessage = "Please provide a value for Name field")]
public string Name { get; set; }
}
}
HTML: I'm using Tag helpers to render HTML code.
@model MiddleWareComponents.Models.Student
@{
ViewBag.Title = "Student";
}
<div >
<label asp-for="@Model.Name" ></label>
<div >
<input asp-for="@Model.Name" placeholder="Name">
<span asp-validation-for="@Model.Name" ></span>
</div>
</div>
<div >
<div >
<button type="submit" >Create</button>
</div>
</div>
**Controller:**
----------------
[HttpPost]
public string Student(Student student)
{
if (ModelState.IsValid)
{
return "";
}
else
{
return "";
}
}
At web page, when we go to the view page source, we can see all the HTML with validation error messages and checks,
<form method="post" action="/home/student">
<div >
<label for="Name">Student Name</label>
<input data-val="true" data-val-required="Please provide a value for Name field" id="Name" name="Name" type="text" value="" />
<span data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>
<div >
<div >
<input type="submit" value="Save Student Details" />
</div>
</div>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8OX4l3Ci88lLoVbwSTker9nokg_bR6Cd914Efrrbcj_iXWC_CqwQvVwHuTf74vGW4CnpfZQgzdwX5kQTi3zi1IhXqgFAPKkGgzcFdHvF2-9KKa-ImHFvdkZBJF5-EvuuaRHlZ_QfcKWztr_p75bXQm0" /></form>
</div>
So, when i click on submit button with out filling the field, then the request goes to the control with empty data and at there model.state propert returns false. But the error is not showing at web page and does not restrict the request to the web-page. I'm looking a help to achieve this goal by tag helpers in .Net 6. Any one can help?, thanks.
CodePudding user response:
If your model state is not valid you want to return the view with the view-model instead of the empty string:
[HttpPost]
public string Student(Student student)
{
if (ModelState.IsValid)
{
return RedirectToAction("yourAction", "yourController");
}
else
{
return View(student);
}
}
CodePudding user response:
Accroding to your decription,I think you could check if you have referred the js files and if the js files are in the correct order,you could check this document related for more details:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>