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:
Move your $(document).ready
function to your View like this:
<script type="text/javascript">
$(document).ready(function () {
//Handle Checks of Actions by RoleName Changed
$('div.RoleAccess select').change(function () {
RoleChangeHandler('@Url.Action("RoleDropDownChanged")');
});
});
</script>
Then in your JS file add url parameter to your function and change ajax call:
function RoleChangeHandler(pageUrl) {
$.ajax({
url: pageUrl,
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;
}
This should work as you expected.
If your script resides in a .JS file then this is not going to work as it'll be treated as plain text. You can either move entire script to the view or you can re-factor script so that majority of the script remains in the .JS and you then pass relevant values from the view.
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() }