0

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.

Community
  • 1
  • 1
tcode
  • 5,055
  • 19
  • 65
  • 124
  • why do you have a `dataType:json` ? I don't see any json returned from your Action ? And why does your Action return a View ? – Raphaël Althaus Apr 10 '14 at 14:15
  • @RaphaëlAlthaus Apologies, please see my update. I copied in the Ajax code from a previous app and it actually hit Index method in my Controller, whereas my previous code (see update) didn't. Can you help? Thanks. – tcode Apr 10 '14 at 14:20
  • The problem is not the "go to the controller action", the problem is why do you think that your method is returning json, and why do you return a View ? – Raphaël Althaus Apr 10 '14 at 14:22
  • @RaphaëlAlthaus I know my method isn't returning Json, it was a mistake as stated in previous comment, please see update. Also, I need to return a View, what is wrong with this? – tcode Apr 10 '14 at 14:29
  • @tgriffiths $(this) will be undefined inside ajax call do the way i did in updated answer – Ehsan Sajjad Apr 10 '14 at 14:42
  • also change the type to 'Get' – Ehsan Sajjad Apr 10 '14 at 14:43
  • or add [HttpPost] on your action – Raphaël Althaus Apr 10 '14 at 14:49
  • what do you want to return by the ajax call,In your controller action you are returning a View but in your ajax call you set dataType:"json",this is a conflict – Mir Gulam Sarwar Apr 10 '14 at 14:58
  • if you want to return a view then don't set dataType:"json", because then your ajax call expect to return a json, though you are actually returning html from you controller action – Mir Gulam Sarwar Apr 10 '14 at 15:01
  • what you want to return from your action? – Mir Gulam Sarwar Apr 10 '14 at 15:04
  • @janina A View. I have updated my code, please see updated question. I am no longer returning Json. – tcode Apr 10 '14 at 15:16

4 Answers4

2

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) {

        }

    });
}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • That's true you passing the ID through the URL as well. Don't do that. – CSharper Apr 10 '14 at 14:27
  • @EhsanSajjad I made your changes to my Ajax call (excluding the dataType: json)..however, my Index method does not get called when I select an item from the drop down list? Any ideas? – tcode Apr 10 '14 at 14:33
  • @EhsanSajjad Thanks, I tried your changes but still it doesn't work. I keep getting the Erro Prompt - "An error occurred." – tcode Apr 10 '14 at 14:42
  • what is the error,see in the ajax, call $(this) will be undefined inside ajax call and also set ajax call type 'GET' as your action is get not post – Ehsan Sajjad Apr 10 '14 at 14:44
1

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()

Mir Gulam Sarwar
  • 2,588
  • 2
  • 25
  • 39
0

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);

}
CSharper
  • 5,420
  • 6
  • 28
  • 54
0

*> only write in your Mvc controller funtion this line

Configuration.ProxyCreationEnabled = fals*

e;

Hasnain Mehmood
  • 407
  • 5
  • 4