justiceorjustus justiceorjustus - 1 month ago 8
C# Question

AJAX call from keydown on one text box to populate another text box ASP.NET MVC

I am attempting to populate a textbox from the value in a separate textbox, ie. using the customer account number to auto-populate the customer name. My AJAX is returning the proper results, however it's not getting populated into the other textbox, which is why I suspect my jQuery is wrong.

<div class="form-group">
@Html.LabelFor(model => model.AccountNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.AccountNumber, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AccountNumber, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.CustomerName, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
</div>
</div>


[HttpGet]
public ActionResult GetCustomerName(string RecKey)
{
var result = (from c in db.Customers
where c.RecKey.Equals(RecKey)
select new { c.RecName });
return Json(result, JsonRequestBehavior.AllowGet);
}


Returned JSON (only returning one result that's an exact match):

[{"RecName":"This is a customer name"}]


$(document).ready(function () {
var RecKey;
$(function () {
$("#AccountNumber").keydown(function () {
RecKey = $("#AccountNumber").val();
$.ajax({
type: "GET",
url: 'GetCustomerName',
data: { RecKey: RecKey },
success: function (data) {
if (data) {
//alert(data);
$('#CustomerName').val(data.RecName);
}
}
});
});
});
});


I am rather new to jQuery and have had success with autocomplete on the same textbox, however my searching hasn't found much for me to populate other text boxes. Anyone have any ideas?

Answer

The issue is because the resulting JSON is an array of objects. If you can guarantee that it will only ever return a single object within that array then you can hard-code the index accessor of the array:

success: function (data) {
  if (data) {
    $('#CustomerName').val(data[0].RecName);
  }
}

Alternatively you can amend your C# code to return a single entity instead of an array:

return Json(result.SingleOrDefault(), JsonRequestBehavior.AllowGet); // or FirstOrDefault()