在 ASP.NET MVC 3 中使用 Ajax 和 JsonResult

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9921517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:15:02  来源:igfitidea点击:

Use Ajax and JsonResult in ASP.NET MVC 3

ajaxasp.net-mvcjsonasp.net-mvc-3razor

提问by Saeid

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

我需要使用ajax和Action获取字符串数组或列表,这是我的实现:

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

这是我在 AccessMenuController 中索引操作视图的 html Dom:

<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 Onfailfunction run and alert me "in OnFailRoleChangeHandler", also I check the RoleDropDownChangedAction with breakpoint and that never run, where is the problem?

问题是下拉列表的所有更改只是Onfail函数运行并提醒我“在 OnFailRoleChangeHandler 中”,我还检查了RoleDropDownChanged带有断点的 操作并且从未运行,问题出在哪里?

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

当我通过 chrome 加载页面时,控制台窗口中出现错误: http://MyProject/GlobalAccess/AccessMenu/@Url.Action(%22RoleDropDownChanged%22) 404 (Not Found) jquery-1.7.1.js:8102

回答by Darin Dimitrov

Remove this setting:

删除此设置:

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

You are not sending any JSON to the server.

您没有向服务器发送任何 JSON。

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

如果要保留此设置,请确保向服务器发送有效的 JSON:

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:

根据您的评论,您似乎正在尝试在单独的 javascript 中使用服务器端助手,这是不可能的。这是我给你的建议。首先在生成下拉列表时提供 url:

<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:

然后在您单独的 javascript 文件中:

$(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:

然后当然你可以用当前选择的值替换硬编码的 roleId:

data: { 'roleId': $(this).val() }

回答by Kosta

Move your $(document).readyfunction to your View like this:

$(document).ready像这样将您的功能移动到您的视图中:

<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:

然后在您的 JS 文件中将 url 参数添加到您的函数并更改 ajax 调用:

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.

这应该按您的预期工作。

回答by Kosta

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.

如果您的脚本驻留在 .JS 文件中,那么这将不起作用,因为它将被视为纯文本。您可以将整个脚本移动到视图中,也可以重构脚本以使大部分脚本保留在 .JS 中,然后您从视图中传递相关值。