简体   繁体   English

MVC4无法使用AJAX调用控制器方法

[英]MVC4 Unable to call controller method using AJAX

I have following method in my controller: 我的控制器中有以下方法:

public JsonResult GetRights(string ROLE_ID)
        {
            var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }

this is how I created a dropdownlist 这就是我创建下拉列表的方式

@Html.DropDownList("ddlRoles", new SelectList(ViewBag.Roles, "ROLE_ID", "ROLE_NAME"),"--Select role--", new { onchange = "GetRights(this.value);" })

and finally a javascript snippet for dropdown item change 最后是用于更改下拉菜单项的JavaScript代码段

<script type="text/javascript">
        function GetRights(role_id) {
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetRights")',
                dataType: "json",
                data: { "ROLE_ID" : role_id.toString() }, 
                success: successFunc,
                error: errorFunc
            })
        }

        function successFunc (data) {
            alert("success");
            if (data != null) {
                var vData = data;
            }
        }

        function errorFunc() {
            alert("error");
        };
    </script>

I can see that javascript function is being called while changing selected item but I am not being navigated to method in my controller. 我可以看到更改所选项目时正在调用javascript函数,但没有在控制器中导航到方法。 Can somebody help me whats wrong in there? 有人可以帮我那里有什么问题吗? Thanks 谢谢

This is not the way you should perform GET request with AJAX. 这不是您应该使用AJAX执行GET请求的方式。 In GET, parameters have to be passed in url string, so your url parameter in AJAX should look like: 在GET中,必须在url字符串中传递参数,因此AJAX中的url参数应类似于:

http://someaddress/GetRights?ROLE_ID=sometexthere

You can check in browser console/debugger where do you fire your reqest to. 您可以在浏览器控制台/调试器中签入您的要求的位置。 Also you can manually fire the same request from browser, as this is normal GET. 您也可以从浏览器手动触发相同的请求,因为这是正常的GET。

Figured out that now. 现在想通了。 It was totally stupid me. 这真是愚蠢。 I did commented out the following: 我确实评论了以下内容:

@Scripts.Render("~/bundles/jqueryval")

But I was not be able to see that :(. Included jquery now and everything seems to be correct. Thanks to everybody for their help 但是我看不到:(。现在包含了jQuery,一切似乎都是正确的。感谢大家的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM