javascript - 在控制器上找不到公共操作方法
问题描述
我收到一个错误,提示找不到我的操作方法,但无法找出问题所在。我现在在互联网上搜索了几个小时,但直到现在还没有找到解决方案。
在我看来,我有一个 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 两个将我的变量发送到我的控制器方法。
有人可以帮忙吗?
谢谢!
解决方案
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.
}
})
推荐阅读
- javascript - 制表器更新列数据
- regex - 在 Spring Data 中的 MongoDB 正则表达式中添加选项
- kubernetes - Kubernetes 容器环境
- azure-devops - Gitlab 与 Azure 开发操作管道的集成
- sql - COUNT 来自多列中的 DISTINCT 值
- typescript - 将 --isolatedModules 与 TS 3.2.2 一起使用时无法重新导出类型
- c - 如何在其中定义几个字符串的结构?
- android - 改装电话上的空响应体
- asp.net-core-2.0 - Identity Server 4 - 验证在 iframe 中使用部分应用程序的客户端
- c# - 如何仅检测一次 Unity 3D 碰撞?