1

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?

2
  • It would help if we saw the JSON being returned, but given your GetCustomerName() function I would assume it's an array, so you need to loop through it in the JS Commented Oct 20, 2016 at 14:53
  • @RoryMcCrossan Edited my post. It's returning one exact match. Commented Oct 20, 2016 at 14:56

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

Both of these solutions work, however I've run into a new issue. Say I'm typing 10050 and Cust # 100 = A and Cust # 10050 = B. It will keep A in the Customer Name text box even though the Cust # textbox = 10050.
That's odd as the value should be over-written with the next request. Try keyup instead of keydown. I'd also suggest you avoid the problem entirely and use a button to make the request instead of doing it as the user types - especially if you have similar id's - 100 and 10050 for example.
you can try changing keydown to keyup... it may be using the value without the last character... Also consider either using change instead or adding a 'debouce' as this way you will fire an ajax call every character which is pretty wasteful
Good call on the keyup! I will also research debounce.
0

I think the TextBox helpers only add the name attribute, while your JQuery code is looking for the box by ID.... Try changing;

@Html.TextBoxFor(model => model.CustomerName, new { @class = "form-control" })

to

@Html.TextBoxFor(model => model.CustomerName, new { @class = "form-control", id = "CustomerName" })

You will also need to use either the SingleOrDefault server side or [0] indexer client side as suggested in the other answers - because even though the array only has one item, it is still an array (not an object) so that will need fixed as well.

P.S. A useful tool in debugging stuff like this is pressing F12 to get the developer console up - you can then try typing your jquery code to see if it works directly into the console. As an example if you type $("#CustomerName") do you actually get an object returned? If not - then my answer is the reason why. If so - something else is affecting this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.