开发者

how to display alert message in controller

I am using one controller whic开发者_如何转开发h 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?


You can add the result to ViewData. For example:

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

In your view you can place anywhere:

MVC2:

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

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.

Regards,

Huske


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


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.

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.

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


You may add below code to tell user

Return Content("Data added successfully");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜