I am currently working on a web application using ASP .NET Core 2.0
One of the components in my app is a partial view that includes a form.
To interact with this form, I have an action method within a controller that is triggered by a JS function utilizing AJAX. This action method populates a model and returns the form's partial view along with the corresponding model.
The functionality works smoothly when the model is not populated. However, I encounter an issue when trying to fetch a record from the database after a specific field is filled and then loses focus. The process works initially when the form's model is empty, but once a record is retrieved and the form is populated, the JS function ceases to execute.
In addition, validations for the field also fail to work after loading a record.
Below is the code snippet for the form's partial view:
<form id="myform">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group col-lg-2">
<label asp-for="Client.Name">Client</label>
<input asp-for="Client.Name" id="ClientName" />
</div>
<div class="form-group col-lg-1">
<label asp-for="Cliente.Phone"></label>
<input asp-for="Cliente.Phone" id="Phone"/>
</div>
</form>
The following code snippet represents the JS/AJAX function:
<script>
$("form").on("blur", "#Phone", function () {
var phone = document.querySelector('#Phone').value;
alert('select client by phone=' + phone);
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Home/GetClienteByPhone",
data: "phone=" + phone,
success: function (res) {
$('#myform').html(res);
}
})
});
</script>
Finally, here is the controller action method (Controller=Home):
public IActionResult GetClienteByPhone(string phone)
{
if (!string.IsNullOrEmpty(phone))
{
var model = new FormViewModel();
model.Client = _db.Clients.Where(c => c.Phone == phone).FirstOrDefault();
return PartialView("_Form", model);
}
return PartialView("_Form");
}
In my View, I display the partial view within a div element with the id="myform"
If anyone has insights into why this behavior occurs, please share your thoughts.
Thank you