Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Ajax and JsonResult in ASP.NET MVC 3

I need to get string array or list with ajax and Action, this is my Implementation:

This is my html Dom of view of Index action in AccessMenuController:

<div class="RoleAccess">
   <select name="RoleDropDown">
    <option value="0">Select Role</option>
    <option value="61AD3FD9-C080-4BB1-8012-2A25309B0AAF">AdminRole</option>
    <option value="8A330699-57E1-4FDB-8C8E-99FFDE299AC5">Role2</option>
    <option value="004E39C2-4FFC-4353-A06E-30AC887619EF">Role3</option>
   </select>
</div>

My Controller:

namespace MyProject.Areas.GlobalAccess.Controllers {

public class AccessMenuController : Controller {

    public ActionResult Index() { return View();}

    [HttpPost]
    public JsonResult RoleDropDownChanged(string roleId) {

     Guid RoleId = new Guid(roleId);

    //Some implement

    List<string> actions = new List<string>();
    for(int i = 0; i <= 10; i++) 
            actions.Add(i.ToString());

return Json(actions.ToArray(), JsonRequestBehavior.AllowGet);

   }
  }
}

and the script:

$(document).ready(function () {

//Handle Checks of Actions by RoleName Changed
$('div.RoleAccess select').change(function () {
    RoleChangeHandler();
});

function RoleChangeHandler() {

    $.ajax({
        url: '@Url.Action("RoleDropDownChanged")',
        type: 'POST',
        data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
        dataType: 'json',
        processData: false,
        contentType: 'application/json; charset=utf-8',
        success: function (data) { SuccessRoleChangeHandler(data); },
        error: OnFailRoleChangeHandler
    });
    return false;
}


function SuccessRoleChangeHandler(data) {

    alert("in success role change");

}

function OnFailRoleChangeHandler(result) {
    alert('in OnFailRoleChangeHandler');

}

And the problem is with all change of dropdown just Onfail function run and alert me "in OnFailRoleChangeHandler", also I check the RoleDropDownChanged Action with breakpoint and that never run, where is the problem?

UPDATE

when I load the page by chrome there is an error in console window: http://MyProject/GlobalAccess/AccessMenu/@Url.Action(%22RoleDropDownChanged%22) 404 (Not Found) jquery-1.7.1.js:8102

like image 979
Saeid Avatar asked Dec 28 '22 03:12

Saeid


1 Answers

Remove this setting:

contentType: 'application/json; charset=utf-8',

You are not sending any JSON to the server.

If you want to keep this setting then make sure that you are sending a valid JSON to your server:

data: JSON.stringify({ 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' })

So:

$.ajax({
    url: '@Url.Action("RoleDropDownChanged")',
    type: 'POST',
    data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
    success: SuccessRoleChangeHandler,
    error: OnFailRoleChangeHandler
});

should work (at least it does for me) with the following action:

[HttpPost]
public ActionResult RoleDropDownChanged(Guid roleId) 
{
    var actions = Enumerable.Range(1, 10).Select(x => x.ToString()).ToList();
    return Json(actions);
}

UPDATE:

According to your comments it looks like you are trying to use server side helpers in a separate javascript which is not possible. Here's what I would suggest you. Start by providing the url when generating your dropdown:

<div class="RoleAccess">
    @Html.DropDownListFor(
        x => x.RoleDropDown, 
        Model.Roles, 
        "-- Select role --",
        new { 
            data_url = Url.Action("RoleDropDownChanged") 
        }
   )
</div>

and then in your separate javascript file:

$(document).ready(function() {
    $('div.RoleAccess select').change(function () {
        var url = $(this).data('url');
        $.ajax({
            url: url,
            type: 'POST',
            data: { 'roleId': '61AD3FD9-C080-4BB1-8012-2A25309B0AAF' },
            success: function(result) {
                alert('success');
            },
            error: function() {
                alert('error');
            }
        });        
    });    
});

and then of course you could replace the hardcoded roleId with the currently selected value:

data: { 'roleId': $(this).val() }
like image 111
Darin Dimitrov Avatar answered Jan 16 '23 03:01

Darin Dimitrov