简体   繁体   中英

How to show a “Saved!” message after Redirect() is made..?

I am currently working in a MVC4 project.

Imagine the following scenario:


(1) The user is allowed to add data to multiple tables and after that needs to confirm by hitting the Submit. <input type="submit" value="" id="saveBtn" title="Save" /> The reason there is no value is because I have CSS applied to the Submit.

(2) After that, to avoid a previous bug to prevent a refresh of the page to duplicate data, I need to Redirect the user in my Controller: return Redirect("Edit?Id=" + id);

(3) After the Redirect() is made, I want to show a simple message that says "Saved!" with a delay of 5 seconds . I do not want an alert("Saved!"); .


I currently got a pseudo-solution working but not preferred. It's an simple click function in jQuery:

CSS

.successMessage {
    color: darkgreen;
}

HTML

<div class="successMessage" style="display: none;">Saved!</div>

JS

$('#saveBtn').click(function () {
    $(".successMessage").delay(500).show(0);
});

The problem is that, since I Redirect(); the user, my message cannot be delayed with this "solution". And after a Redirect(); is made, the message will not show up again.

What is a better approach in order to get a 'delayed' message? Thanks in advance.

Add a TempData in your submit action,and show the delay message in your view by confirm if TempData has value when page is ready.

Action:

//save info
TempData["Message"]="Saved!";
return Redirect("Edit?Id=" + id)

View:

string message=TempData["Message"]==null?"":TempData["Message"].ToString();
@if(message!="")
{
    <div class="successMessage" style="display: none;">@message</div>
    <script type='text/javascript'>
      $(document).ready(function(){
         $(".successMessage").delay(500).show(0);
      })
    </script>
}

The best solution to show notification messages is to use TempData["Message"] to store values and on every page do this-

 if (TempData["Message"] != null)
 {
   ViewBag.Message = TempData["Message"];
 }

Now in the View,

        <div>
            @if (ViewData["Message"] != null)
            {
                <div>Saved!</div>
            }
       </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM