从 C# MVC 调用 jQuery 函数

Calling jQuery function from C# MVC

如何从 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>

编辑: 如果用户单击发布按钮并且没有文件被 selected 那么我想显示 jquery ui 对话框弹出框告诉他们 select 一个文件。我需要这一行 uploadedSongs.Count(x => x.IsSelected) == 0 来检查他们是否还没有 selected 文件。无论如何,我可以将其放入我的 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");
            }
        }

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

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>
}