I'm building an MVC 5 web application which has a drop down list contained within the layout template. I have followed this answer on stackoverflow and it works well MVC 3 Layout Page, Razor Template, and DropdownList
What I need is for the User to select an item (persons name) from the drop down list, a JQuery call to be made which then passes the selected drop down list ID into a method within a Controller.
I have a drop down list declared like this
@Html.DropDownListFor(x => x.SelectedUserID, Model.UserList, "Select", new { @class = "form-control" })
When an item is selected, the following JQuery code is called
$(document).ready(function () {
$("#SelectedUserID").change(ChangeEventOfDDL);
function ChangeEventOfDDL() {
alert("test val" + $(this).val());
$.ajax({
type: "POST",
url: '/Dashboard/Index/' + $(this).val(),
data: { id: $(this).val() },
dataType: "json",
error: function () {
alert("An error occurred.");
},
success: function (data) {
}
});
}
});
This then passes the selected ID to the Index method in my Controller
public ActionResult Index(int? id)
{
DashboardViewModel model = new DashboardViewModel();
if(id == null || id == 0)
{
User user = _userService.GetUserByID(Convert.ToInt32(User.Identity.GetUserId()));
model.SelectedUser = user;
}
else
{
model.SelectedUser = _userService.GetUserByID(id.Value);
}
return View(model);
}
This all seems to work fine. When I debug through my code I can see the selected Drop Down List ID being passed through the code as expected all the way to the Index method in my Controller. The problem is, when I complete stepping through the code and return to the UI, a JQuery error occurs with a prompt stating "An error occurred.". This is the default error message I have set in my JQuery function.
Because this error occurs my code doesn't work properly.
I have no idea why this is happening, can anyone please help?
Thanks.
UPDATE
Before using the Ajax call inside of the ChangeEventOfDLL Function I had used the following code, however, it never actually hit the Index method in the Dashboard.
$.post('@Url.Action("Dashboard", "Index")', { id: $(this).val() }, function (result) {
});
UPDATE
I change my JQuery to this
$(document).ready(function () {
$("#SelectedUserID").change(ChangeEventOfDDL);
function ChangeEventOfDDL() {
alert("test val" + $(this).val());
$.post('@Url.Action("Index", "Dashboard")', { id: $(this).val() }, function (result) {
});
}
});
But still the Index method does not get called in the Controller.
Next I updated the JQuery code to this
$(document).ready(function () {
$("#SelectedUserID").change(ChangeEventOfDDL);
function ChangeEventOfDDL() {
alert("test val" + $(this).val());
$.ajax({
type: "POST",
url: '@Url.Action("Index","Dashboard")',
data: { id: $(this).val() },
error: function () {
alert("An error occurred.");
},
success: function (data) {
}
});
}
});
But still the Index method is not called in the Controller and I still get the Error Prompt.