0

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?

0

2 Answers 2

1

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)
       }
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Tnx, I remove ValidateAntiForgeryToken and it's work correctly. But why?!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.