问题
I am trying to use the change event of a dropdown to call an ActionResult in my controller in order to populate another dropdown.
Here is the jQuery that I've tried:
$(function () {
$('#CertificationId').change(function () {
var data = {
certificationId: $('#CertificationId').val()
};
var certificationId = $('#CertificationId').val();
// $.post('@Url.Action("AjaxGetCourseOptions", "WorkerCertifications")', {certificationId : certificationId}, $(this).parents('form:first').serialize(), function (data) {
// //$('#form').children().remove().append(data);
// }, 'html');
// var url = '@Url.Action("AjaxGetCourseOptions", "WorkerCertifications")';
// var certificationId = $('#CertificationId').val();
// $.post(url, { certificationId: certificationId }, function (result) {
// alert('success');
// });
// $.getJSON('/WorkerCertifications/AjaxGetCourseOptions/SysAdmin/Worker/Certifications/14843/', data, function (result) {
// alert(result.message);
// });
$.getJSON('@Url.Action("AjaxGetCourseOptions", "WorkerCertifications")', data, function (result) {
alert(result.message);
});
// $.getJSON(this.href, data, function (result) {
// alert(result.message);
// });
return false;
});
});
Here is the code from the Controller:
public ActionResult AjaxGetCourseOptions( string certificationId )
{
var viewData = new WorkerCertificationViewModel
{
//CourseOptions = ScheduledCourse.GetActive().ToSelectList(x => x.Id, x => x.Id),
CourseOptions = ScheduledCourse.GetAvailableCourses(Convert.ToInt64(certificationId)).ToSelectList(x => x.Id, x => x.Id)
};
viewModel.CourseOptions = viewData.CourseOptions;
return Json( new {message = "Test"},
JsonRequestBehavior.AllowGet
);
}
I can't seem to get the jQuery to call the code in the Controller. How can I accomplish this?
Update
I am still having an issue getting this to work. This is the url of the page before the change event fires for the dropdown http://mylocalhost.com/camms/WorkerCertifications/Insert/SysAdmin/Worker/Certifications/14843
After the change event fires, I have a hard coded (for now) url that I want to post to but it's getting appended to the current url. Any idea how to fix this? This is the url that it is trying to post to: http://mylocalhost.com/camms/WorkerCertifications/Insert/SysAdmin/Worker/Certifications/camms/WorkerCertifications/AjaxGetCourseOptions/SysAdmin/Worker/Certifications/14843/?certificationId=10916
The url should look like this: http://mylocalhost.com/camms/WorkerCertifications/AjaxGetCourseOptions/SysAdmin/Worker/Certifications/14843/?certificationId=10916
I had to remove the local host and port in order to save this update.
回答1:
I accomplished this by the following:
Jquery:
$(function () {
$('#CertificationId').change(function (evt) {
var data = {
certificationId: $('#CertificationId').val()
};
var certificationId = $('#CertificationId').val();
$.ajax({
//url: "/camms/WorkerCertifications/GetCourseOptions/SysAdmin/Worker/Certifications/14843",
url: window.location.href.replace('Insert', 'GetCourseOptions'),
type: 'POST',
data: { certificationId: certificationId },
success: function (courseOptions) {
// courseOptions is your JSON array
var $select = $('#CourseId');
$select.children().remove();
if (courseOptions.length > 0) {
var listItems = [];
for (var i = 0; i < courseOptions.length; i++) {
listItems.push('<option value="' +
courseOptions[i].Value + '">' + courseOptions[i].Text + '</option>');
}
$select.append(listItems.join(''));
}
// $.each(courseOptions, function (i, option) {
// $('<option>', {
// value: option.Id
// }).html(option.Id).appendTo($select);
// });
}
});
return false;
});
});
In the Controller:
[HttpPost]
public JsonResult GetCourseOptions( string certificationId = "0")
{
var list = ScheduledCourse.GetAvailableCourses(Convert.ToInt64(certificationId)).ToSelectList(x => x.ScheduledCourseId, x => x.ScheduledCourseId);
var result = new JsonResult();
result.Data = list.ToList();
return result;
}
回答2:
In my application, I'm populating the dropdown list like this:
There are two dropdown lists job categories and jobs. Once you select a job category the jobs list gets populated.
function ListingJobs()
{
var job_ID = $( "#JobCatID" ).val();
$.ajax( {
url: '@Url.Action("GetJobs")',
data: { JobCatID: job_ID },
dataType: "json",
type: "POST",
error: function ()
{
alert( "An error occurred." );
},
success: function ( data )
{
var items = "";
$.each( data, function ( i, item )
{
items += "<option value=\"" + item.values + "\">" + item.texts + "</option>";
} );
$( '#JobID' ).html( items );
}
} );
}
$( '#JobCatID' ).change( function ()
{
ListingJobs();
} );
And in your controller you must supply a value-name pair converted to json.
来源:https://stackoverflow.com/questions/15505364/how-to-use-jquery-change-event-on-dropdownlist-to-populate-another-dropdownlist