locked
Status Message using view state bag. RRS feed

  • Question

  • User-501297529 posted

    I previously was using a TempDataKey to display a status message when a vote was submitted on a view. Now I want to update that to use View state bag instead. How do I do that using the same jquery that the previous status message I was using. That status message used jquery to show the message and then fade out. Is there a better way to do it? 

    Here is how the previous status message was setup:

    View:

    @{
        ViewData["Title"] = "Cast Vote";
        Layout = "~/Views/Shared/_Layout.cshtml";
        var statusMessage = TempData.Get<StatusMessageModel>(TempDataKey.Vote.AddMessage);
    }
    <br/>
    <h2 class="text-info">@ViewData["Title"]</h2>
    <hr />
    
    <div class="form-group col-md-8">
        <div asp-validation-summary="All" id="validation-error" class="custom-validation-summary"></div>
        <input id="packet-item-id" asp-for="@Model.PacketItemId" type="hidden" />
        <input id="voting-type" asp-for="@Model.VotingType" type="hidden" />
    </div>
    
    <form method="post"
          id="form-vote"
          enctype="multipart/form-data">
        <div class="row">
            <div class="col-lg-8 col-md-12 col-sm-12">
    
                <partial name="_ClientStatusMessage" />
                <partial name="_StatusMessage" for="@statusMessage" />
                <div id="add-edit-vote">
                    <partial name="_Vote" model="@Model" />
                </div>
            </div>
        </div>
    

    StatusMessage Partial view with fade out jquery:

    @if (Model != null && Model.Messages.Count > 0) 
    {
        var statusMessageClass =  Model.IsError ? "danger" : "success";
        <div class="alert alert-@statusMessageClass alert-dismissible" role="alert" id="status-message">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            @{
                if (Model.Messages.Count > 1)
                {
                    <ul>
                        @foreach (var message in Model.Messages)
                        {
                            <li> @message </li>
                        }
    
                    </ul>
                }
                else
                {
                    @Model.Messages[0]
                }
            }
        </div>
    }
    <script language="javascript">
        window.setTimeout(function () {
            if ($("#status-message").hasClass("alert-success"))
            {
                $(".alert").fadeTo(500, 0).slideUp(500, function () {
                    $(this).remove(); 
                    });
                }
            }, 2000);
    

    Controller:

    public async Task<IActionResult> Vote(VoteViewModel voteViewModel, CancellationToken cancellationToken)
            {
                if (ModelState.IsValid)
                    try
                    {
    
                       ....
    
                                voteViewModel.VoteId = (await _discussionService.FindVoteOnThisPacketItemByUserAsync(packetItem.PacketItemId, user.Id, cancellationToken)
                                .ConfigureAwait(true)).VoteId;
    
                                TempData.Put(key: TempDataKey.Vote.AddMessage,
                                   StatusMessageModel.Create(UserStringsService.VoteAddedSuccessfully, false));
                                return View("Vote", voteViewModel);
                            }).ConfigureAwait(true);
                                
                        }).ConfigureAwait(true);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex, "Error in registering the vote for packet item: " +
                                            $"{voteViewModel.PacketItemId}");
                    }
    
                return View("Vote", voteViewModel);
    
            }

    Here is the new view and controller I have so far with the View State:

    @{
        ViewData["Title"] = "Cast Vote";
        Layout = "~/Views/Shared/_Layout.cshtml";
       
    }
    <br/>
    <h2 class="text-info">@ViewData["Title"]</h2>
    <hr />
    
    <div class="form-group col-md-8">
        <div asp-validation-summary="All" id="validation-error" class="custom-validation-summary"></div>
        <input id="packet-item-id" asp-for="@Model.PacketItemId" type="hidden" />
        <input id="voting-type" asp-for="@Model.VotingType" type="hidden" />
    </div>
    
    <form method="post"
          id="form-vote"
          enctype="multipart/form-data">
        <div class="row">
            <div class="col-lg-8 col-md-12 col-sm-12">
    
                <partial name="_ClientStatusMessage" />
                @ViewData["Message"]
                
                <div id="add-edit-vote">
                    <partial name="_Vote" model="@Model" />
                </div>
            </div>
        </div>
    

    Controller:

    public async Task<IActionResult> Vote(VoteViewModel voteViewModel, CancellationToken cancellationToken)
            {
                if (ModelState.IsValid)
                    try
                    {
                         
    ...... ViewData["Message"] = "Your vote is registered successfully."; return View("Vote", voteViewModel); }).ConfigureAwait(true); }).ConfigureAwait(true); } catch (Exception ex) { Logger.LogError(ex, "Error in registering the vote for packet item: " + $"{voteViewModel.PacketItemId}"); } return View("Vote", voteViewModel); }

    Monday, December 21, 2020 10:42 PM

Answers

  • User1312693872 posted

    Hi,bootzilla

    This is the demo, after submit, the messages will show:

    Make sure that Viewdata is written in the page which returned by the controller.

    Index.cshtml:

    <form asp-action="Vote">
        <input asp-for="VoteId" />
        <input type="submit" value="submit" />
        @if (ViewData["Message"] != null)
        {
            <div class="alert alert-success alert-dismissible" role="alert" id="status-message">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                @ViewData["Message"]
            </div>
        }
    </form>
    @section Scripts
    {
        <script language="javascript">
            window.setTimeout(function () {
                if ($("#status-message").hasClass("alert-success")) {
                    $(".alert").fadeTo(500, 0).slideUp(500, function () {
                        $(this).remove();
                    });
                }
            }, 2000);
        </script>
    }
    

    Controller:

    [HttpPost]
    public IActionResult Vote(VoteViewModel vm)
    {
    ..... ViewData["Message"] = "Your vote is registered successfully."; return View("Index"); }

    Result:

    Best Regards,

    Jerry Cai

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 22, 2020 9:23 AM