【问题标题】:Calling jQuery function from C# MVC从 C# MVC 调用 jQuery 函数
【发布时间】:2015-09-26 13:05:48
【问题描述】:

如何从 C# 调用 Jquery 函数?我曾尝试使用 registerStartupScript,但我不明白它是如何工作的,而且它仍然无法工作。根本不进入jquery函数

Page page = new Page();
ScriptManager.RegisterStartupScript(page, this.GetType(), "script", "publishDialog();", true);
function publishDialog() {
    $(".alert").dialog({
        modal: true,
    });
}
<div class="alert">
    You must be signed in to upload music
</div>

编辑: 如果用户单击发布按钮并且没有选择文件,那么我想显示 jquery ui 对话框弹出框,告诉他们选择一个文件。我需要这一行uploadedSongs.Count(x =&gt; x.IsSelected) == 0 来检查他们是否没有选择文件。无论如何,我可以将它放入我的 jquery 函数中吗?

[HttpPost]
     public ActionResult Publish(IEnumerable<UploadedSong> uploadedSongs)
        {
            Page page = new Page();
            if (uploadedSongs.Count(x => x.IsSelected) == 0)
            {
                ScriptManager.RegisterStartupScript(page, this.GetType(), "script", "publishDialog();", true);
                return View("../Users/UserProfile", uploadedSongs);
            }
            else
            {
                return RedirectToAction("../Home/Index");
            }
        }

【问题讨论】:

  • 您很少需要从服务器端运行客户端脚本。两者是完全不同的野兽。您要实现的总体目标是什么?
  • 看看这个:stackoverflow.com/questions/4994040/… 我认为它有答案。

标签: jquery asp.net-mvc call


【解决方案1】:

您不应该尝试像这样注册启动脚本。相反,您应该在您的模型上设置一个由您的视图逻辑解释的值。像这样的:

var myViewModel = new MyViewModel();
myViewModel.NeedsToRunJs = true; //some logic
return View(myViewModel);

然后在 Razor 视图中:

@if(Model.NeedsToRunJs)
{
    <script>
        /* js to run */
    </script>
}

或者,如果您希望 javascript 是外部的,请添加 src:

@if(Model.NeedsToRunJs)
{
    <script src="someFile.js"></script>
}

【讨论】:

  • 如果可能的话,我希望有另一种方式,而不是将脚本放在视图中,而不是将它们放在外部 js 文件中
  • 然后改用&lt;script src="someFile.js"&gt;&lt;script&gt;
  • 另外,在视图中包含视图逻辑比在控制器中包含 javascript 函数要好得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 2013-10-01
相关资源
最近更新 更多