I am learning ASP.NET Core (on .NET 5.0). I have recently used form HTML helper with model validation. But something doesn't seem right. Although the validation fails, client still calls the action and a request is sent to the server. Why?
Whatever the reason is, I'm looking for a way to prevent submitting to action. I have found this which helped me to prevent submitting. But the problem is, this way I cannot have the client-side validation. In other words, my validation messages don't show and this solution merely prevents form submitting.
So how can I configure ASP.NET form HTML helper (or possibly the submit button) not to submit when the validation fails on the client side and still show the validation error messages?
The following is a portion of my view code:
<fieldset>
@using(Html.BeginForm())
{
@Html.ValidationSummary()
<p>
@Html.LabelFor(x => x.Title)
@Html.EditorFor(x => x.Title)
@Html.ValidationMessageFor(x => x.Title)
</p>
<p>
@Html.LabelFor(x => x.Body)
@Html.TextAreaFor(x => x.Body)
@Html.ValidationMessageFor(x => x.Body)
</p>
<p>
<button type="submit">Create</button>
</p>
}
</fieldset>
Although the validation fails, client still calls the action and a request is sent to the server. Why?
The issue might be relates the following reasons:
Client-side validation script not load.
By default, Asp.net core application Client-side validation using JQuery Validation plugin and jQuery Unobtrusive Validation library. So, we have to add the related references.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
Besides, the above script references also in the _Layout.cshtml and _ValidationScriptsPartial.cshtml page, you could also use these views.
For example: Create.cshtml
@model WebApplication6.Data.Employee
@{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Create</h1>
<h4>Employee</h4>
<hr />
<div class="row">
<div class="col-md-4">
@using (Html.BeginForm("Create","Home", FormMethod.Post))
{
@Html.ValidationSummary()
<p>
@Html.LabelFor(x => x.EmpName)
@Html.EditorFor(x => x.EmpName)
@Html.ValidationMessageFor(x => x.EmpName)
</p>
<p>
@Html.LabelFor(x => x.Description)
@Html.TextAreaFor(x => x.Description)
@Html.ValidationMessageFor(x => x.Description)
</p>
<p>
<button type="submit">Create</button>
</p>
}
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Browser disabled JavaScript.
Perhaps the browser disabled JavaScript, so, it cause the client scripts not working, try to check the browser setting or try to use another browser to verify it. If that issue relates the browser, try to enable the JavaScript.