javascript - 从 View 中的 javascript 调用 Controller 操作

标签 javascript jquery asp.net

我想使用 JavaScript 从 View 中调用操作,但我不能这样做: 这是我的代码:

@if (ViewBag.Status == true)
{
   <script language="javascript" type="text/javascript">
       if (confirm("Some message"));
       //And here i want to add action call
   </script>
}

我正在尝试使用@Html.Action,但是这个损坏的脚本代码和确认消息没有显示。 当我如下所示编写它时:Calling ASP.NET MVC Action Methods from JavaScript :

    @if (ViewBag.Status == true)
    {
       <script language="javascript" type="text/javascript">
           if (confirm("Some message"));
           {
                 $.ajax({
                        url: 'MyController/MyAction',
                        data: { id: id },
                        success: function () {
                            alert('Added');
                        }
                 });
          }
       </script>
    }

没有任何改变。它显示确认对话框但不调用方法

最佳答案

您需要将代码更改为类似这样的内容。在这种情况下,您将调用:func(@ViewBag.Status)

@Section scripts
    <script language="javascript" type="text/javascript">
        //val in this case being the value of the ViewBag passed from where the call is occurring
        function func(val) {
            if (val == true) {
                if (confirm("Some message"));
                {
                    $.ajax({
                        url: 'MyController/MyAction',
                        data: { id: id },
                        type: "POST",
                        success: function () {
                            alert('Added');
                        }
                    });
                }
            }
        }
    </script>
end section

同样在 Controller 中记得在方法上应用 [HttpPost] 属性,如下所示:

[HttpPost]
public ActionResult MyAction(string id)
{
    // your code
    return Json();//your response
}

关于javascript - 从 View 中的 javascript 调用 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30191179/

相关文章:

javascript - api yandex 映射到 WordPress 网站的不同页面

javascript - 为什么我的 react-router 链接会把我带到页面中间?

javascript - 为什么 RequireJs 传递的是 Null?

ASP.NET:即使使用必需的字段验证器,自定义验证也不起作用

jquery - 使用 Get 进行 ajax 调用会出现 500 错误

c# - 大数据损坏的 excel 文件

javascript - JavaScript 中循环的奇怪行为

javascript - ASP.NET MVC - Javascript 数组总是作为 null 传递给 Controller

javascript - 使用 bundle.config bundle 2 个具有相同名称和参数的函数的 .js 文件后会发生什么?

javascript - jquery,javascript,html div相关查询