Search code examples
c#viewbag

Auto-Hide ViewBag Message in C# after 15 seconds


I am displaying a message via ViewBag in C# and it works fine. Now what I want is to auto Hide the ViewBag message after 15 seconds. How should I do that?

Following is my code where I am using ViewBag:

public ActionResult ForgetPassword(String EmailId, string message)
    {
        ViewBag.Message = message;
        ForgetPassword objForgetPassword = new ForgetPassword { EmailId = EmailId };
        return View();
    }

//Other Model where I am passing the Message

 if (objResult.Status)
            {
                return RedirectToAction("Login", new { message = "Password changed Successfully. Please Login with the New Password."});
            }

CSHTML code for the same:

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal for-pass">
    <h4><b>@ViewBag.Message</b></h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.OTP, htmlAttributes: new { @class = "control-label" })
        <div class="col-md-12">
            @Html.EditorFor(model => model.OTP, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.OTP, "", new { @class = "text-danger" })
        </div>
    </div>

Solution

  • You can use the javascript setTimeout function to run the code to hide the message using the query fadeOut function:

    $(document).ready(function(){
        setTimeout(function(){
            $("#msg").fadeOut();
        }, 15000);
    });
    

    and in view:

    <h4 id="msg"><b>@ViewBag.Message</b></h4>
    

    here's fiddle: https://dotnetfiddle.net/3Sw1O9