Reputation: 561
I am trying to do a look up with Ajax and a dropdown list, The user enters a postcode in a text box, then clicks search. From here I want to populate a dropdown list, with the values coming from the database, The action is in a separate controller :-
public ActionResult Search(string Pcode)
{
return Json(new[] {
new { value = '1', text = "text 1" },
new { value = '2', text = "text 2" },
new { value = '3', text = "text 3" }
});
}
My HTML:
Pcode:- @Html.TextBox("GPPOST")
GP Practice:
@Html.EditorFor(model => model.Patient.GPSurgery)
<br/>
@Html.DropDownListFor(m =>m.Patient.GPSurgery Enumerable.Empty<SelectListItem>(),"-- Select GP --")
GP : <input type="button" id="SearchPcode" value="Search">
And finally the Ajax:
$(function () {
$('#SearchPcode').click(function () {
// get the new value
var value = $(this).val();
// and send it as AJAX request to the action
$.ajax({
url: '/GP_Practices/Search', //'<%= Url.Action("Search", "GP_Practices") %>',
type: 'POST',
data: { pcode: value },
success: function (result) {
// when the AJAX succeeds refresh the dropdown list with
// The JSON values returned from the controller action
var GPNames = $('#Patient.GPSurgery');
GPNames.empty();
$.each(result, function(index, item) {
alert(item.text);
});
$.each(result, function (index, item) {
GPNames.append(
$('<option/>', {
value: item.value,
text: item.text
}));
});
}
});
});
});
When I run the code I do get the Json results back, (which I can see in the alert box).
My 2 problems are:
1)I cannot seem to pass the value from the text box Html.TextBox("GPPOST")
2)The Dropdown list is not refreshing with the new values.
Upvotes: 1
Views: 4811
Reputation: 56429
1)I cannot seem to pass the value from the text box Html.TextBox("GPPOST")
That's because your Javascript passes pcode
, yet your controller expects Pcode
(casing matters).
Also as Ehsan Sajjad mentions, you're not sending the value of the textbox, but this unearths a bigger problem: You're binding two fields to the same model property, you can't do that. You'll have to use a separate field for your dropdown and your search input.
2)The Dropdown list is not refreshing with the new values.
That's because your jQuery selector is incorrect:
var GPNames = $('#Patient_GPSurgery');
Upvotes: 1