Home Simple jquery ajax call to controller: what is causing 500 Internal server error?
Reply: 1

Simple jquery ajax call to controller: what is causing 500 Internal server error?

harveyAJ
1#
harveyAJ Published in 2018-01-12 15:53:45Z

I know that there are a lot of similar questions here on SO, but none of the ones I have read could help me solve my problem.

I have a drop down list with several items to choose from, the change of selection should trigger a method call in the controller OnItemSelectedChange(string itemName)

View (~/Home/Views/Index.cshtml)

@Html.DropDownListFor(model => model.SelectedItem, new 
SelectList(@Model.Items), new { onchange = "SelectedItemChanged(this);" })

jquery

function SelectedItemChanged(selectObj) {
        itemName = selectObj.value;
        $.ajax({
            type: 'POST',
            url: '/Home/OnSelectedItemChanged/?itemName=' + itemName,
        }).done(function () {
            alert('Modified item');
        });
    }

Controller's action (~/Controllers/HomeController)

[HttpPost]
public ActionResult OnSelectedItemChanged(string itemName)
{
    // do stuff 
    return View(new MyModel {...});
}

The javascript is being called fine, but POST Home/OnSelectedItemChanged?itemName=item3 returns "500 Internal Server Error".

I believe the problem is in the routing to the controller method, yet I thought MVC auto-populated the parameters

harveyAJ
2#
harveyAJ Reply to 2018-01-12 18:02:13Z

Well that was a silly mistake, obviously. Thanks @ADyson in the comments for suggesting to have a look at the "response" tab of the ajax request, which stated "the View 'OnSelectedItemChanged' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/OnSelectedItemChanged.aspx
~/Views/Home/OnSelectedItemChanged.ascx [...]"

When I return my View in my controller, I should specify the view name so that the proper location is searched i.e. changing:

[HttpPost]
public ActionResult OnSelectedItemChanged(string itemName)
{
    // do stuff 
    return View(new MyModel {...});
}

into

[HttpPost]
public ActionResult OnSelectedItemChanged(string itemName)
{
    // do stuff 
    return View("Index", new MyModel {...});
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.255731 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO