Karim Pazoki
Karim Pazoki

Reputation: 969

The jquery ajax doesn't work (the server side is ASP.net)

I have a problem in my code. The jquery ajax does not work. My jquery script is like this:

$('#AddPermission').click(function () {
    var _permissionId = $('#PermissionId').val();            
    var _roleId = $('#Role_Id').val();
    if (_permissionId == '') {
        return false;
    }
    var _parameters = { permissionId: _permissionId, id: _roleId };
    console.log(_parameters);
    $.ajax({
        url: "/Admin/AddPermission2RoleReturnPartialView",
        type: "GET",
        data: _parameters,
        success: function (data, textStatus, jqXHR) {
            console.log(data);
            $('#PermissionsTable').html(data);
            $('#PermissionId').val("");
        },
        error: function (xhr, textStatus, errorThrown){
            console.log(errorThrown);
        }
    });
});

My server-side script written in ASP is this:

 [HttpGet]
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        [ValidateAntiForgeryToken]
        public PartialViewResult AddPermission2RoleReturnPartialView(int id, int permissionId)
        {
            Response.Write("Code1");
            ROLE role = database.ROLES.Find(id);
            PERMISSION _permission = database.PERMISSIONS.Find(permissionId);
            
            if (!role.PERMISSIONS.Contains(_permission))
            {
                role.PERMISSIONS.Add(_permission);
                database.SaveChanges();
            }
            return PartialView("_ListPermissions", role);
        }

When running this in console, I gave these data:

Object { permissionId: "39", id: "3" }

Internal Server Error

Can anybody help me please?

Upvotes: 0

Views: 301

Answers (2)

Aditya
Aditya

Reputation: 89

If you does have AntiForgeryToken in html than you have to send it in parameters for example if i have a method in my controller like

[AcceptVerbs(HttpVerbs.Post)] 
[ValidateAntiForgeryToken]
public ActionResult GetResult(int? id, int? someValue)
{
   return PartialView("TestPartial");
}

And in view html looks like

<div class="somediv">
@Html.AntiForgeryToken()
<button class="btn btn-primary" id="btnTest">Test Me</button>
</div>
<div id="someId"></div>

Finally jquery code will be

$("#btnTest").click(function (e) {
     e.preventDefault();
      var p = { id: 123, someValue: 1234, __RequestVerificationToken: 
               $("input[name='__RequestVerificationToken']").val() };
      $.ajax({
         type: "POST",
         url: "@Url.Action("GetResult", "ControllerName")",
         data: $.param(p),
         dataType: "application/json",
         complete: function (data) {
              $("#someId").empty().append(data.responseText);
          }
       });
 });

Make sure method accept verb type should be POST

Upvotes: 0

Aditya
Aditya

Reputation: 89

Remove ValidateAntiForgeryToken attribute on the method as you are not posting form with Token just making an ajax call, and try to wrap parameters of ajax call using param function of jquery

$.ajax({
       url: "@Url.Action("ActionName", "ControllerName")",
       type: "GET",
       data: $.param(_parameters),
       success: function (data, textStatus, jqXHR) {
        console.log(data); 
       },
       error: function (xhr, textStatus, errorThrown) {
        console.log(errorThrown)
       }
  });

Upvotes: 1

Related Questions