admin管理员组

文章数量:1310254

In Cshtml the following doesn't work

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

How can i achieve this

In Cshtml the following doesn't work

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

How can i achieve this

Share Improve this question edited Mar 19, 2015 at 7:21 Satpal 133k13 gold badges167 silver badges170 bronze badges asked Mar 19, 2015 at 7:14 Suhas ARSuhas AR 391 gold badge1 silver badge8 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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

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

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

Use

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

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

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

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

本文标签: javascriptHow to display alert message in view page using viewbagStack Overflow