显示mvc5的tempdata消息作为bootbox警告消息

时间:2015-04-15 11:31:06

标签: html5 asp.net-mvc-4 bootbox

我是MVC的新手,我想从Controller tempdata中显示一条警告消息作为bootbox警告消息

怎么做?请有人帮我一个例子

2 个答案:

答案 0 :(得分:0)

说你有TempData["Message"]

在您的视图中,将其分配给某些hiddenField,如下所示

@{
var message=TempData["Message"] as string;
}
<input type="hidden" value="@message" id="hdnMessage"/>

现在编写一个document.ready函数,检查隐藏字段是否有值,如果是,则显示如下消息:

$(document).ready(function(){
     if($("#hdnMessage").val()!="")
     {
         var msg=$("#hdnMessage").val();
         bootbox.alert(msg);
         $("#hdnMessage").val('');//empty the value so that it won't show everytime
     }
});

答案 1 :(得分:0)

假设视图中使用了<script>标记,您可以直接将TempData中的值注入JavaScript。像这样的东西会起作用:

@if(TempData.ContainsKey("Message"))
{
    <script>
        $(function(){ 
            bootbox.alert('@TempData["Message"]');
        });
    </script>
}

赢了在.js文件中工作,因为Razor引擎无法对其进行解析。

您可以将其置于局部视图中,或将其包含在_Layout中的某个位置,或者只是在您当前正在使用的视图中使用它。唯一重要的一点是要记住它需要在jQuery之后呈现,bootstrap.js和bootbox.js。