Question

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.

Was it helpful?

Solution

you are passing datatype:jsonwhile you are returning view from action, and another mistake is you are passing id in data attribute as well and in url as well, this is also wrong: this should be:

$.ajax({
    type: "POST",
    url: '/Dashboard/Index/' + $(this).val(),
    data: { id: $(this).val() },
    dataType: "json",
    error: function () {
        alert("An error occurred.");
    },
    success: function (data) {

    }

});

like this:

var id = $(this).val();
$.ajax({
    type: "POST",
    url: '@Url.Action("Index","Dashboard")',
    data: { id: id  },
    error: function () {
        alert("An error occurred.");
    },
    success: function (data) {

    }

});

Note: Always use Url.Action helper you create the action url so that it will not create issues on live deployment.

if you want to return only object not view then do like this:

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 JsonResult(model,JsonRequestBehavior.AllowGet);
    }

and then you have to put dataType:'json' in the ajax call.

Update:

Make ddl event like this:

$("#SelectedUserID").change(function(){

ChangeEventOfDDL($(this).val());

});

your function:

function ChangeEventOfDDL(id)
{
 $.ajax({
        type: "POST",
        url: '@Url.Action("Index","Dashboard")',
        data: { id: id  },
        error: function () {
            alert("An error occurred.");
        },
        success: function (data) {

        }

    });
}

OTHER TIPS

Then Remove dataType:"json" from you ajax set up

And in your action use return PartialView("ViewName",model) instead of return View("ViewName",model)

In case you return partial view else return view()

It is going in to the error function because you have specified the datatype as JSON hence dataType: 'json' But you are not returning JSON back to the function you are returning a view and thats why the error is thrown. Change your Action Result to a Json result and do this.

public JsonResult(int? id)
{
         // blah blah blah
       return Json(model.SelectedUser, JsonRequestBehavior.AllowGet);

}

*> only write in your Mvc controller funtion this line

Configuration.ProxyCreationEnabled = fals*

e;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top