<form id="formElem">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="ID" type="hidden" />
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" required class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" required rows="5" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label asp-for="ImageData" class="control-label"></label>
<input asp-for="ImageData" type="file" class="form-control" />
<span asp-validation-for="ImageData" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group col-sm-3">
<input type="submit" id="dataSend" name="btn" value="Save" class="btn btn-primary" />
</div>
</form>
JS:
$("#dataSend").on('click', function (e) {
e.preventDefault();
var formData = new FormData();
formData.append('ImageData', $('#ImageData')[0].files[0]);
formData.append('ID', document.getElementById('ID').value);
formData.append('Name', document.getElementById('Name').value);
formData.append('Description', document.getElementById('Description').value);
formData.append('btn', 'Save');
$.ajax({
contentType: false,
processData: false,
type: 'POST',
url: '/Products/AddProduct',
data: formData,
success: function (response) {
window.location.href = "/Products/Index";
},
error: function () {
console.log("error.");
},
});
});
When I click on the save button, it directly calls the AddProduct
action, though all form fields are blank. My question is, why my model is not validated, despite there is a [Required]
Annotation on the Name
and Description
fields in the model class. This happens when I use JavaScript.
Also, I used jquery.validate.unobtrusive.min.js
and jquery.validate.min.js
files.
e.preventDefault();
will prevent the form validation as well. To check for validation without submitting a form use valid()
. In case of error as $("#formElem").valid() is not a function.
, check if jquery.validate.min.js
is included.
As
$("#dataSend").on('click', function (e) {
e.preventDefault();
$("#formElem").valid();
...
Further in your AddProduct method, have you checked for the Model state? Such as
if (!ModelState.IsValid)
{
//Don't add product
// return page();
}