从 VB.Net 代码隐藏调用 "Sweet Alert"的 Javascript 警报

标签 javascript jquery asp.net vb.net

在我的应用程序中,我使用 Sweet Alerts 触发 javascript 警报来自 VB.Net 代码后面的各种页面加载和事件。我可以毫无问题地触发基本警报,如下所示:

Dim script As String = String.Format("swal('Welcome , " + Username + "');")

ScriptManager.RegisterClientScriptBlock(Page, GetType(System.Web.UI.Page), "redirect", script, True)

还有其他可用的警报,其中涉及在警报的引号内添加对象:

swal({   
         title: "Sweet!",   
         text: "Here's a custom image.",   
         imageUrl: "images/thumbs-up.jpg" 
    });

所以我的问题是,当我想在后面的代码中使用它时,我无法知道在正确的位置添加引号,该对象似乎会导致语法错误

Dim script As String = String.Formatswal({   title: "Sweet!",   text: "Here's a custom image.",   imageUrl: "images/thumbs-up.jpg" });

ScriptManager.RegisterClientScriptBlock(Page, GetType(System.Web.UI.Page), "redirect", script, True)

enter image description here

最佳答案

从 VB.NET/服务器端的 Angular 来看,JavaScript 都不是代码,它只是在响应中发出的字符串。因此,首先,提供给 String.Format() 的所有内容都必须位于 VB.NET 字符串中,并带有双引号:

Dim script As String = "just a string to VB";

从那时起,您只需尝试使字符串的内容完全符合客户端上有效 JavaScript 的需要。有两种处理方式:

字符串中任何需要引号字符 (") 的地方,请使用两引号 (""):

Dim script As String = "<script>swal({title:""Sweet!"", text:""Here's a custom image."", imageUrl:""images/thumbs-up.jpg""});</script>"

或者,第二种方式:JavaScript 允许使用单引号 (') 或双引号 (")。由于 VB.NET 不认为单引号是特殊字符,因此只需将所有 JavaScript 双引号替换为单引号即可引用:

Dim script As String = "<script>swal({title:'Sweet!', text:'Here's a custom image.', imageUrl:'images/thumbs-up.jpg'});</script>"

最后,String.Format 用于轻松地将变量值插入到字符串中。它使用 {0} {1} {2} 等作为替换值。然后将变量作为附加参数传递。这就是为什么您必须转义 {} 字符。这是一个例子:

Dim script As String = String.Format("<script>swal({{title:'{0}', text:'{1}', imageUrl:'{2}'}});</script>", strTitle, strText, strImageUrl)

关于从 VB.Net 代码隐藏调用 "Sweet Alert"的 Javascript 警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33587443/

相关文章:

javascript - ASP.NET多用户控制客户端ID问题

jquery - 如何使用 jQuery 通过 Ajax 使用 Google 翻译?

javascript - 我怎样才能正确使用 jQuery 来修复这个 fencepost 案例?

c# - 如何通过IP地址范围限制页面访问?

asp.net - 如何将XML文件转换成DataSource?

javascript - Android onOrientationChange 在方向完成之前触发(太早)

javascript - 没有类型的cshtml脚本标签

c# - 将 DTO 传输到 ViewModel

javascript - 如何在用户按 Enter 时触发 Tab

javascript - Asual $.address - 如何摆脱主题标签