Reputation: 769
I am currently working on changing the contents of a drop down list using ajax and jquery, and filling from a database. Using jquery, I can clear and add to the drop down just fine. My problem comes when trying to hit the controller to hit the database for the information needed to fill the second drop down.
How can I make this work? I've spent three days reading through other SO questions in the hopes of finding the answer, and here is the jquery code I have thus far:
$('#Vehicle_KovId_value').change(function () {
var kovID = $(this).val();
if (kovID != null && kovID != '') {
$('#Vehicle_BodyStyle_value').get(0).options.length = 0;
$('#Vehicle_BodyStyle_value').get(0).options[0] = new Option('Please Select One', '-1');
$.ajax({
type: "POST",
url: "AjaxController/Index",
async: true,
data: "{KovID:" + kovID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#Vehicle_BodyStyle_value').get(0).options.length = 0;
$('#Vehicle_BodyStyle_value').get(0).options[0] = new Option("Please Select One", "-1");
alert("Worked!");
$.each(msg.d, function (index, item) {
$('#Vehicle_BodyStyle_value').get(0).options[$('#Vehicle_BodyStyle_value').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
$('#Vehicle_BodyStyle_value').get(0).options.length = 0;
alert("Failed to load styles");
}
});
}
});
I've tried a few different url setups in the above code, such as:
url: "@Url.Action('AjaxController', 'Index')",
url: "/AjaxController/Index",
url: "/Controllers/AjaxController/Index",
url: "Controllers/AjaxController/Index"
For reference, though we haven't really done anything with the controller yet, here's the code for the controller:
Namespace NoticeOfSale
Public Class AjaxController
Inherits System.Web.Mvc.Controller
'
' GET: /Ajax
Function Index() As ActionResult
Return View()
End Function
End Class
End Namespace
I'm not sure if I've just got the wrong syntax or if I'm finding syntax for later versions of MVC, as I am using MVC 2.
Upvotes: 0
Views: 5295
Reputation: 769
The problem here was in the call.
$.ajax({
type: "POST",
url: "AjaxController/Index",
async: true,
data: "{KovID:" + kovID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
Both the type and the url were incorrect. I should have been:
$.ajax({
type: "GET",
url: '/Ajax/Index',
async: false,
data: { KovID: kovID },
contentType: "application/json; charset=utf-8",
dataType: "json",
Upvotes: 3