javascript 如何使用 viewbag 在视图页面中显示警报消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29138999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:07:23  来源:igfitidea点击:

How to display alert message in view page using viewbag

javascriptalert

提问by Suhas AR

In Cshtml the following doesn't work

在 Cshtml 中以下不起作用

ViewBag.alert = @"<script language='javascript'>alert('Plan Already Exists');</script>";

How can i achieve this

我怎样才能做到这一点

回答by Dana Carrubba

I am using MVC Razor with C#, and I got this logic to work in my view by updating it a bit:

我正在将 MVC Razor 与 C# 一起使用,并且通过稍微更新它使此逻辑在我的视图中起作用:

@if (!string.IsNullOrEmpty(ViewBag.Message))
{
    <script type="text/javascript">
        alert("@ViewBag.Message");
    </script>
}

回答by Satpal

You need to pass ViewBag.alertas string to alert()function. Currently you are assign string to ViewBag.alert

您需要将ViewBag.alert字符串作为字符串传递给alert()函数。目前您将字符串分配给ViewBag.alert

Use

利用

<script>
    alert('@ViewBag.alert');
</script>

回答by Rahul Tripathi

You need to add a message to the ViewBag in your controller.

您需要向控制器中的 ViewBag 添加一条消息。

 public ActionResult Index() {
            ViewBag.Message = "Plan Already Exists";
            return View();
        } 

And then in your view, add a bit of script:

然后在您看来,添加一些脚本:

 <% if (!string.IsNullOrEmpty(ViewBag.Message)) { %>
    <script type="text/javascript">
        alert('<%=ViewBag.Message%>');
    </script>
<% } %>

回答by belal ahmad

You Can Use Like this:

你可以这样使用:

Controller:

控制器:

public ActionResult Index()
{
    ViewBag.msg = "View Bag Value";

    return View();
}

View:

看法:

if (!string.IsNullOrEmpty(ViewBag.msg))
{
     <script type="text/javascript">alert('@ViewBag.msg');</script>
}