I am trying to send back the value of a selected item in Drop Down List back to an Action method in my controller using jQuery Ajax in an MVC4 web application. I have a Drop Down List called MeditechDropDown and here is my jQuery function that is not quite working. I manage to reach my Action method but the value coming in is null.
jQuery(document).ready(function () {
$("#MeditechDropDown").change(function () {
$.ajax({
url: "/Home/PopulateEmailAddressUI",
data: JSON.stringify('id=' + $(this).val()), // Send value of the drop down change of option
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
// Variable data contains the data you get from the action method
}
});
});
});
The action name is PopulateEmailAddressUI. Will someone kindly shed some light on what I am doing wrong? I know I am not writing my jQuery function correctly. Many thanks.
I have written some successful jQuery ajax calls in .NET MVC4. This is what they look like:
$('#projectList').on('click', 'li', function () {
pid = $(this).data('id');
$.ajax({
type: 'POST',
url: '/Admin/GetProject',
data: '{ id: ' + pid + ' }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
projectRetrieved(data);
}
});
});
Controller:
[HttpPost]
public ActionResult GetProject(int id) {
string connStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
string sql = "SELECT * FROM [Portfolio] WHERE [id] = @id";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.SelectCommand.Parameters.Add(new SqlParameter("@id", id));
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
da.Dispose();
conn.Close();
return Json(objConv.DataTableToArrayList(dt), JsonRequestBehavior.AllowGet);
}