Reputation: 184
With the script below I call an action method for managing the permission of users. On the first time everything works, but when I debug the controller my variable grp
gets the value of usr
.
My view code
<body>
<div class="container">
<br />
<table class="table table-responsive table-bordered">
@{
int count = 1;
//inizialize my ef context
dev_labelsEntities db = new dev_labelsEntities();
//get all users stored in the db
var users = from u in db.Users
orderby u.username
select new
{
u.username
};
//get all groups from the db
var groups = from g in db.Groups
orderby g.group_name
select new
{
g.group_name
};
<tr>
<th>Username</th>
@foreach (var item in groups)
{
<td>@Html.DisplayFor(model => item.group_name)</td>
}
</tr>
foreach (var item in users)
{
<tr>
<td>@Html.DisplayFor(model => item.username)</td>
@foreach (var itemG in groups)
{
//in the input tag i define the values which i want to get
<td><input type="checkbox" class="chkclass"
username="@item.username" groupname="@itemG.group_name"
id="@count" />
count++;
</td>
}
</tr>
}
}
</table>
</div>
</body>
This is my JQuery
$(document).ready(function() {
$('.chkclass').click(function() {
var getchkid = $(this).attr('id');
var isChecked = $('#' + getchkid).is(':checked');
if ($('#' + getchkid).is(':checked') == true) {
// to be send to your call
var username = $(this).attr('username');
var groupname = $(this).attr('groupname');
//here put your call ajax to your action
$.ajax({
type: 'Post',
url: '/UserGroups/ManagePermission',
dataType: 'json',
data: {
'usr': username,
'grp': groupname
},
success: function(data) {},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
})
}
});
});
The code in the controller is only for testing that everything works.
Does anyone have any idea why I get this behaviour?
EDIT
After get in the method without any operations
Here the for is complete and look at to the values of variables
EDIT 2
Here the values sent from the client
Upvotes: 0
Views: 529
Reputation: 1997
Couple of things that might help.
I think its good practice to make an object to catch the fields like this:
public class ManagePermissionsRequest {
public string usr { get; set; }
public string gpr { get; set; }
}
Then in the controller add a [FromBody] to the request:
[HttpPost]
public ActionResult ManagePermissions([FromBody]permissionsRequest) {
// Your code
}
I think that would do the trick. Sometimes though I need to stringify the data in JQuery, so thats worth a try if it still isn't working:
$.ajax({
type: 'Post',
url: '/UserGroups/ManagePermission',
dataType:'json',
data: JSON.stringify({
'usr': username,
'grp': groupname
}),
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
})
Note: Its good practice to avoid abbreviating variables. I might go with "user" or "username" instead of usr
Upvotes: 3