首页 > 解决方案 > 在控制器上找不到公共操作方法

问题描述

我收到一个错误,提示找不到我的操作方法,但无法找出问题所在。我现在在互联网上搜索了几个小时,但直到现在还没有找到解决方案。

在我看来,我有一个 JavaScript 函数:

<script type="text/javascript">
function ShowHideAds(button) {
    var dAds = document.getElementById("dAds");

    if (dAds.style.display == "none") {
        dAds.style.display = "block"

        var txtBox = "Visible";
        $.post('@Html.Action("GetState","Rights")', { txtAds: txtBox });
    }
    else {
        dAds.style.display = "none"

        var txtBox = "Hidden";
        $.post('@Html.Action("GetState", "Rights")', { txtAds: txtBox });
    }
   } </script>

我在文本框和列表框之间切换,根据哪个可见,我想将参数传递给我的方法。

我在控制器中的方法如下:

[HttpPost, ActionName("GetState")]
        public ActionResult GetState(string txtAds, string txtRg)
        {
            if (txtAds != null)
                stateTxtAds = txtAds;
            if (txtRg != null)
                stateTxtRg = txtRg;

            return View();
        }

最后这是我的路由:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

在使用 @Html.Action() 方法之前,我有以下代码行:

$.post("/Rights/GetState", { txtAds: txtBox });

但这在部署项目时不起作用,所以我尝试使用@Html.Action 两个将我的变量发送到我的控制器方法。

有人可以帮忙吗?

谢谢!

标签: javascriptasp.netpostmodel-view-controller

解决方案


GetState(string txtAds, string txtRg)有两个参数,但您只提供一个。如果您希望它接受两个但只提供一个,就像您在通话中所做的那样,请执行以下操作。

例如对于帖子@Html.Action("GetState", "Rights")', { txtAds: txtBox }

GetState(string txtAds, string txtRg = "")

这样,您可以txtAds根据需要发送并且它应该到达它。

我推荐的ajax:

var json = '{txtAds: "' + txtAds + '"}'

$.ajax({
    url:'@Url.Action("GetState", "Rights")',
    type:'POST',
    data: json,
    contentType: 'Application/json',
    success: function(result){
        // Whatever you want to do next.
    }
})

推荐阅读