asp.net-mvc 如何在控制器中显示警报消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6463675/
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-09-08 01:17:12  来源:igfitidea点击:

how to display alert message in controller

asp.net-mvcmodel-view-controllerasp.net-mvc-2

提问by Saloni

I am using one controller which is inserting values in the database. I want to display alert message from controller when the values insertesd in the database successfully. Is it possible. If yes then how?

我正在使用一个在数据库中插入值的控制器。当值成功插入数据库时​​,我想显示来自控制器的警报消息。是否可以。如果是,那么如何?

采纳答案by melaos

Basically that depends on how are you inserting the value into the database, as you would need a method to tells you whether the insertion was successful. As there's a few ways to do that now, linq/entity framework/sql/etc.

基本上,这取决于您如何将值插入数据库,因为您需要一种方法来告诉您插入是否成功。由于现在有几种方法可以做到这一点,linq/entity framework/sql/etc.

Then after you know whether did the insertion happens, then you can just assign a value to a variable and then from the code/aspx just check the value and do a simple alert.

然后在您知道插入是否发生后,您只需为变量赋值,然后从代码/aspx 中检查该值并执行简单的警报。

<script type="text/javascript">
//i'm using jquery ready event which will call the javascript chunk after the page has completed loading
$(document).ready(function(){
//assuming that your variable name from the code behind is bInsertSuccess
var bSuccess = "<%= bInsertSuccess %>";
if(bSuccess){
    alert("Successfully Inserted");
}
});
</script>

回答by Husein Roncevic

You can add the result to ViewData. For example:

您可以将结果添加到 ViewData。例如:

if (SaveToDbOK)
{
    ViewData["Success"] = "Data was saved successfully.";
   // Do other things or return view
}

In your view you can place anywhere:

在您看来,您可以在任何地方放置:

MVC2:

MVC2:

<% if (ViewData["Success"] != null) { %>
    <div id="successMessage">
        <%: ViewData["Success"] %>
    </div>
<% } %>

MVC3:

MVC3:

@if (ViewData["Success"] != null) {
    <div id="successMessage">
        @ViewData["Success"]
    </div>
@}

I used this approach in my last project in order to make the information returned from the server unobtrusive. Checking whether ViewData["Success"] or ViewData["Failure"] are done in the Master page, the divs are formatted using CSS, jQuery code was used to hide the notifications after 5 seconds.

我在上一个项目中使用了这种方法,以使从服务器返回的信息不显眼。检查是否在母版页中完成了 ViewData["Success"] 或 ViewData["Failure"],div 使用 CSS 格式化,使用 jQuery 代码在 5 秒后隐藏通知。

Regards,

问候,

Huske

哈士奇

回答by shahnila

public ActionResult UploadPropertyImage()
{
    // Business logic....
    return Content("<script language='javascript' type='text/javascript'>alert('Save Successfully');</script>");
}

回答by catdog01

You may add below code to tell user

您可以添加以下代码告诉用户

Return Content("Data added successfully");