locked
How to make button as html instead of an ajax button RRS feed

  • Question

  • User-501297529 posted

    I want to make this delete-vote button as an html button instead of ajax. I currently am using javascript to delete the vote. When I click Delete button, a modal window to confirm that I want to delete comes up and then once I click confirm it delete the vote. How can I make this delete-vote button an html button?

    View

    <input id="voting-id" asp-for="@Model.VoteId" type="hidden" />
    <div asp-validation-summary="All" id="validation-error" class="text-danger custom-validation-summary"></div>
    <div class="card">
        <div class="card-body">
    
            @{
                if (@Model.PacketItemDetails != null)
                {
                    if (@Model.PacketItemDetails.PacketItemFileId != null
                        && @Model.PacketItemDetails.PacketItemFileId != 0)
                    {
                        <a asp-action="DownloadFile" class="orange"
                           target="_blank"
                           asp-controller="Asset"
                           asp-route-id="@Model.PacketItemDetails.PacketItemFileId ">
                            @Model.PacketItemDetails.Title
                        </a>
                    }
                    else
                    {
                        <div class="forum-orange">@Model.PacketItemDetails.Title</div>
                    }
    
                }
            }
    
            <p id="vote-status" class="card-text forum-blue">
    
                @{if (@Model.VoteId != 0)
                    {
                        <text>
                            <br />You have already voted on this item.
                            <br />Change by clicking Re-cast Vote or delete vote by clicking Delete Vote
                        </text>
                    }
                    else
                    {
                        <text><br />You have not voted on this item yet. Vote by selecting an option and clicking Vote.</text>
                    }
                }
            </p>
            @{
                if (Model.AvailableVotingOptions != null)
                {
                    @Html.DropDownListFor(m => m.VotingOptionId,
                        // 1. Store selected value in Model.VotingOptionId
                        // when page is rendered after postback,
                        // take selected value from Model.VotingOptionId.
    
                        // 2. Take list of values from Model.AvailableVotingOptions
                        Model.AvailableVotingOptions,
    
                        // 3. Text for the first 'default' option
                        "- Please select a vote -",
    
                        //4. A class name to assign to <select> tag
                        new { @class = "form-control", @id = "voting-options" })
                }
            }
            <div id="div-discuss-content" style="display: none">
                <br />
                <div class="control-label">Discuss Content</div>
                <textarea id="discuss-content" class="discuss-content" asp-for="Comments"></textarea>
            </div>
        </div>
        <div class="card-footer">
            <div class="row">
                <div class="col-sm-12 col-md-3 col-lg-3">
                    <button type="submit"
                            class="btn btn-success btn-sm col-sm-12"
                            id="vote-button"
                            data-action="submit">
                        <i class="fas fa-vote-yea fa-fw"></i>
                        @if (@Model.VoteId != 0)
                        {
                            <text>Re-Cast Vote</text>
                        }
                        else
                        {
                            <text>Vote</text>
                        }
    
                    </button>
                </div>
                    <div class="col-sm-12 col-md-3 col-lg-3">
                        <a data-toggle="modal"
                           id="delete-vote-button"
                           data-id="@Model.VoteId"
                           href="#delete-vote-modal"
                           class="btn btn-danger btn-sm delete-vote col-sm-12">
                            <i class="fa fa-trash fa-fw"
                               title="Delete"
                               style="color: white"></i>Delete Vote
                        </a>
                    </div>
                    <div class="col-sm-12 col-md-3 col-lg-3">
                        <button type="button"
                                class="btn btn-forum btn-sm col-sm-12"
                                id="back-to-packet">
                            <i class="fas fa-arrow-alt-circle-left fa-fw"></i>
                            Back To Packet
                        </button>
                    </div>
                </div>
        </div>
    </div>
    <!-- start: Delete vote modal -->
    <!-- Modal -->
    <div class="modal fade" id="delete-vote-modal" tabindex="-1" role="dialog" data-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Vote</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="voteId" id="voteId" value="" />
                    Do you want to delete this vote ?
                    <div style="text-align: center; display: none" id="loaderDiv">
                        <img src="~/images/loading.gif" width="150" />
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>
                    <button class="btn btn-success" id="confirm-delete-vote" type="button">Confirm</button>
                </div>
            </div>
        </div>
    </div>

    Controller

      public async Task<JsonResult> DeleteVote(long id, CancellationToken cancellationToken)
            {
                try
                {
                    await _discussionService.DeleteVoteAsync(
                            id,
                            cancellationToken)
                        .ConfigureAwait(true);
                    //return RedirectToAction(nameof(Vote));
                    return Json(new { isSuccess = true, statusMessage = UserStringsService.VoteDeletedSuccessfully });
                }
                catch
                {
                    Logger.LogError($"Error in deleting the Vote Id: {id}");
                    return Json(new { isSuccess = false, statusMessage = UserStringsService.VoteDeleteFailed });
                }
            }

    js

    $(document).on("click",
            ".delete-vote",
            function() {
                var voteId = $(this).data('id');
                $(".modal-body #voteId").val(voteId);
            });
    
        /**
       * This function is called when Confirm is clicked from the Confirm modal to delete the vote
       */
        $(document).on("click",
            '#confirm-delete-vote',
            function(e) {
                var voteId = parseInt($(".modal-body #voteId").val());
                var packetItemId = $('#packet-item-id').val();
                var votingType = $('#voting-type').val();
    
                var data = {
                    id: voteId
                };
                $.ajax({
                    type: "POST",
                    url: "/Discussion/deletevote",
                    data: data,
                    success: function(response) {
                        $("#delete-vote-modal").modal("hide");
                        if (response.isSuccess) {
                            ShowDeleteItemStatus(response.isSuccess, response.statusMessage);
                            location.href = "/Discussion/Vote?packetItemId=" + packetItemId + " &votingType=" + votingType;
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        $("#delete-vote-modal").modal("hide");
                        ShowDeleteItemStatus(false, response.statusMessage);
                        location.href = "/Discussion/Vote?packetItemId=" + packetItemId + " &votingType=" + votingType;
                    }
                });
            }); 

    Sunday, January 3, 2021 7:48 PM

Answers

  • User-501297529 posted

    I'm not sure if this is what I'm looking for. What I want to accomplish is when I click 'Confirm' on the modal window that the vote is deleted using html instead of ajax. I want to replace ajax with html. How do I do that? Does that make sense what I'm asking?

    I tried this on the Confirm button by removing the ajax but it doesn't work

    Confirm button on modal 

    <div class="modal fade" id="delete-vote-modal" tabindex="-1" role="dialog" data-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Vote</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="voteId" id="voteId" value="" />
                    Do you want to delete this vote ?
                    <div style="text-align: center; display: none" id="loaderDiv">
                        <img src="~/images/loading.gif" width="150" />
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>
                    <a
                        class="btn btn-success"
                        asp-action="DeleteVote"
                        asp-controller="Discussion"
                        asp-route-id="@Model.VoteId"
                        >Confirm</a>
                    @*<button class="btn btn-success" id="confirm-delete-vote" type="button"  asp-route-accountKey="@Model.VoteId">Confirm</button>*@
                </div>
            </div>
        </div>
    </div>

    Controller

     [HttpPost]
            public async Task<IActionResult> DeleteVote(long id, CancellationToken cancellationToken)
            {
                try
                {
                    await _discussionService.DeleteVoteAsync(
                            id,
                            cancellationToken)
                        .ConfigureAwait(true);
                    //return RedirectToAction(nameof(Vote));
                    return Json(new { isSuccess = true, statusMessage = UserStringsService.VoteDeletedSuccessfully });
                }
                catch
                {
                    Logger.LogError($"Error in deleting the Vote Id: {id}");
                    return Json(new { isSuccess = false, statusMessage = UserStringsService.VoteDeleteFailed });
                }
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 4, 2021 6:12 PM

All replies

  • User1686398519 posted

    Hi bootzilla, 

    I want to make this delete-vote button as an html button instead of ajax.

    <a data-toggle="modal" id="delete-vote-button" data-id="@Model.VoteId" href="#delete-vote-modal" 
    class="btn btn-danger btn-sm delete-vote col-sm-12"><i class="fa fa-trash fa-fw"

    Do you want to modify the way to trigger Modal?

    1. Generally speaking, to trigger a modal, you need to use use a button or a link.Then include the two data-* attributes:
      1. data-toggle="modal" opens the modal window
      2. data-target="#myModal" points to the id of the modal
      3. <button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>
    2. You can also trigger Modal via JavaScript.
      • $('#myModal').modal('show')
    3. Note: You can click this link to view the usage of Bootstrap's modal.

    The following is an example of triggering modal using data attributes, you can refer to it.

    <button data-toggle="modal"
       id="delete-vote-button"
       data-id="test"
       data-target="#delete-vote-modal"
       class="btn btn-danger btn-sm delete-vote col-sm-12">
        <i class="fa fa-trash fa-fw"
           title="Delete"
           style="color: white"></i>Delete Vote
    </button>
    <div class="modal fade" id="delete-vote-modal" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Understood</button>
                </div>
            </div>
        </div>
    </div>

    Here is the result. 

    Best Regards,

    YihuiSun

    Monday, January 4, 2021 8:03 AM
  • User-501297529 posted

    I'm not sure if this is what I'm looking for. What I want to accomplish is when I click 'Confirm' on the modal window that the vote is deleted using html instead of ajax. I want to replace ajax with html. How do I do that? Does that make sense what I'm asking?

    I tried this on the Confirm button by removing the ajax but it doesn't work

    Confirm button on modal 

    <div class="modal fade" id="delete-vote-modal" tabindex="-1" role="dialog" data-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Vote</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="voteId" id="voteId" value="" />
                    Do you want to delete this vote ?
                    <div style="text-align: center; display: none" id="loaderDiv">
                        <img src="~/images/loading.gif" width="150" />
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>
                    <a
                        class="btn btn-success"
                        asp-action="DeleteVote"
                        asp-controller="Discussion"
                        asp-route-id="@Model.VoteId"
                        >Confirm</a>
                    @*<button class="btn btn-success" id="confirm-delete-vote" type="button"  asp-route-accountKey="@Model.VoteId">Confirm</button>*@
                </div>
            </div>
        </div>
    </div>

    Controller

     [HttpPost]
            public async Task<IActionResult> DeleteVote(long id, CancellationToken cancellationToken)
            {
                try
                {
                    await _discussionService.DeleteVoteAsync(
                            id,
                            cancellationToken)
                        .ConfigureAwait(true);
                    //return RedirectToAction(nameof(Vote));
                    return Json(new { isSuccess = true, statusMessage = UserStringsService.VoteDeletedSuccessfully });
                }
                catch
                {
                    Logger.LogError($"Error in deleting the Vote Id: {id}");
                    return Json(new { isSuccess = false, statusMessage = UserStringsService.VoteDeleteFailed });
                }
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 4, 2021 6:12 PM
  • User-474980206 posted

    Wrap the button with a form, and make the button type a submit. Place the ID in a hidden field in the form. Have the form action post to the delete action. The delete action should redirect to the page’s get action to redisplay the page.

    Tuesday, January 5, 2021 1:03 AM
  • User1686398519 posted

    Hi bootzilla, 

    1. <a>:Only the Get method can be used.
    2. If you want to use the Post method, you can use <form> to submit.
    3. Here are two solutions, you can refer to them.
      • You can use TempData to store data. This property stores data until it's read in another request.

    Controller

            //The first method
            [HttpGet]
            public async Task<IActionResult> DeleteVoteGet(long id, CancellationToken cancellationToken)
            {
                try
                {
    ... ... //delete data TempData["isSuccess"] = true; TempData["statusMessage"] = "VoteDeletedSuccessfully"; return RedirectToAction("Index"); } catch { TempData["isSuccess"] = false; TempData["statusMessage"] = "VoteDeleteFailed"; return RedirectToAction("Index"); } } //The second method [HttpPost] public async Task<IActionResult> DeleteVotePost(long id, CancellationToken cancellationToken) { try { ... ... //delete data TempData["isSuccess"] = true;                
    TempData["statusMessage"] = "VoteDeletedSuccessfully"; return RedirectToAction("Index"); } catch { TempData["isSuccess"] = false; TempData["statusMessage"] = "VoteDeleteFailed"; return RedirectToAction("Index"); } }

    View

    @{
        ViewData["Title"] = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h1>Index</h1>
    @if (TempData["isSuccess"] != null)
    {
        @if ((bool)TempData["isSuccess"])
        {
            <div class="alert alert-success" role="alert">
                @TempData["isSuccess"]-@TempData["statusMessage"]
            </div>
        }
        else
        {
            <div class="alert alert-danger" role="alert">
                @TempData["isSuccess"]-@TempData["statusMessage"]
            </div>
        }
    }
    @* The first method *@
    <button data-toggle="modal"
            id="delete-vote-button"
            data-id="123"
            data-target="#delete-vote-modalGet"
            class="btn btn-danger btn-sm delete-vote col-sm-12">
        <i class="fa fa-trash fa-fw"
           title="Delete"
           style="color: white"></i>Delete VoteGet
    </button>
    <div class="modal fade" id="delete-vote-modalGet" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">delete-vote-modalGet</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <a class="btn btn-success" asp-action="DeleteVoteGet" asp-controller="TestConfirm" asp-route-id="1">Confirm</a>
                </div>
            </div>
        </div>
    </div>
    
    <br /><br /><br /><br />
    @* The second method *@
    <button data-toggle="modal"
            id="delete-vote-button"
            data-id="123"
            data-target="#delete-vote-modalPost"
            class="btn btn-danger btn-sm delete-vote col-sm-12">
        <i class="fa fa-trash fa-fw"
           title="Delete"
           style="color: white"></i>Delete VotePost
    </button>
    <div class="modal fade" id="delete-vote-modalPost" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <form asp-controller="TestConfirm" asp-action="DeleteVotePost" method="post">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="staticBackdropLabel">delete-vote-modalPost</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <input hidden name="id" value="1" />
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Confirm</button>
                    </div>
                </div>
            </div>
        </form>
    </div>
    

    Here is the result. 

    Best Regards,

    YihuiSun

    Tuesday, January 5, 2021 5:20 AM
  • User-501297529 posted

    Wrap the button with a form, and make the button type a submit. Place the ID in a hidden field in the form. Have the form action post to the delete action. The delete action should redirect to the page’s get action to redisplay the page.

    Are you saying this should go on the Confirm button on the modal form or the delete button to get to the modal form? I put this on the confirm button but all that does is submit the form as if I submitted a vote. It doesn't delete the vote. This what I updated the Confirm button to

    <form asp-controller="Discussion" asp-action="DeleteVote" method="get" asp-route-id="@Model.VoteId">
                        <button class="btn btn-success" id="confirm-delete-vote" type="submit">Confirm</button>
                    </form>

    When I debug it submits the post action for the Vote method since the form is called Vote.cshtml and should go to the DeleteVote post action, right?

    Tuesday, January 5, 2021 5:54 AM
  • User-501297529 posted

    YihuiSun

    Hi bootzilla, 

    1. <a>:Only the Get method can be used.
    2. If you want to use the Post method, you can use <form> to submit.
    3. Here are two solutions, you can refer to them.
      • You can use TempData to store data. This property stores data until it's read in another request.

    Controller

            //The first method
            [HttpGet]
            public async Task<IActionResult> DeleteVoteGet(long id, CancellationToken cancellationToken)
            {
                try
                {
                    ... ... //delete data
                    TempData["isSuccess"] = true;
                    TempData["statusMessage"] = "VoteDeletedSuccessfully";
                    return RedirectToAction("Index");
                }
                catch
                {
                    TempData["isSuccess"] = false;
                    TempData["statusMessage"] = "VoteDeleteFailed";
                    return RedirectToAction("Index");
                }
            }
            //The second method 
            [HttpPost]
            public async Task<IActionResult> DeleteVotePost(long id, CancellationToken cancellationToken)
            {
                try
                {
                    ... ... //delete data
                    TempData["isSuccess"] = true;                 
                    TempData["statusMessage"] = "VoteDeletedSuccessfully";
                    return RedirectToAction("Index");
                }
                catch
                {
                    TempData["isSuccess"] = false;
                    TempData["statusMessage"] = "VoteDeleteFailed";
                    return RedirectToAction("Index");
                }
            }

    View

    @{
        ViewData["Title"] = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h1>Index</h1>
    @if (TempData["isSuccess"] != null)
    {
        @if ((bool)TempData["isSuccess"])
        {
            <div class="alert alert-success" role="alert">
                @TempData["isSuccess"]-@TempData["statusMessage"]
            </div>
        }
        else
        {
            <div class="alert alert-danger" role="alert">
                @TempData["isSuccess"]-@TempData["statusMessage"]
            </div>
        }
    }
    @* The first method *@
    <button data-toggle="modal"
            id="delete-vote-button"
            data-id="123"
            data-target="#delete-vote-modalGet"
            class="btn btn-danger btn-sm delete-vote col-sm-12">
        <i class="fa fa-trash fa-fw"
           title="Delete"
           style="color: white"></i>Delete VoteGet
    </button>
    <div class="modal fade" id="delete-vote-modalGet" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">delete-vote-modalGet</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <a class="btn btn-success" asp-action="DeleteVoteGet" asp-controller="TestConfirm" asp-route-id="1">Confirm</a>
                </div>
            </div>
        </div>
    </div>
    
    <br /><br /><br /><br />
    @* The second method *@
    <button data-toggle="modal"
            id="delete-vote-button"
            data-id="123"
            data-target="#delete-vote-modalPost"
            class="btn btn-danger btn-sm delete-vote col-sm-12">
        <i class="fa fa-trash fa-fw"
           title="Delete"
           style="color: white"></i>Delete VotePost
    </button>
    <div class="modal fade" id="delete-vote-modalPost" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <form asp-controller="TestConfirm" asp-action="DeleteVotePost" method="post">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="staticBackdropLabel">delete-vote-modalPost</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <input hidden name="id" value="1" />
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary">Confirm</button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    Here is the result. 

    Best Regards,

    YihuiSun

    I'm not sure I quite understand. Are you saying use the DeleteVotePost button to delete the vote that I should use a form to submit but it is better to use DeleteVoteGet? If I use Get in my controller action method does that change from this

    public async Task<JsonResult> DeleteVote(long id, CancellationToken cancellationToken)
            {
                try
                {
                    await _discussionService.DeleteVoteAsync(
                            id,
                            cancellationToken)
                        .ConfigureAwait(true);
                    //return RedirectToAction(nameof(Vote));
                    return Json(new { isSuccess = true, statusMessage = UserStringsService.VoteDeletedSuccessfully });
                }
                catch
                {
                    Logger.LogError($"Error in deleting the Vote Id: {id}");
                    return Json(new { isSuccess = false, statusMessage = UserStringsService.VoteDeleteFailed });
                }
            }

    to 

     public async Task<IActionResult> DeleteVote(long id, CancellationToken cancellationToken)
            {
                try
                {
                    await _discussionService.DeleteVoteAsync( id, cancellationToken) .ConfigureAwait(true);
                    TempData["isSuccess"] = true;
                    TempData["statusMessage"] = "VoteDeletedSuccessfully";
                    return RedirectToAction("Index");
                }
                catch
                {
                    TempData["isSuccess"] = false;
                    TempData["statusMessage"] = "VoteDeleteFailed";
                    return RedirectToAction("Index");
                }
            }

    Edit: I tried this and just like bruce's solution it just refreshes the page and it doesn't delete the vote.

    The view page is called Vote.cshtml and when I hit the Confirm button it posts back to the Vote view page. When I debug it goes to the Vote post method in the controller instead of the DeleteVote method in the controller to delete the vote.

    Here is what I have currently in the view for the Delete button and Modal View:

    <button data-toggle="modal"
                            id="delete-vote-button"
                            data-id="@Model.VoteId"
                            data-target="#delete-vote-modal"
                            class="btn btn-danger btn-sm delete-vote col-sm-12">
                        <i class="fa fa-trash fa-fw"
                           title="Delete"
                           style="color: white"></i>Delete Vote
                    </button>
    <!-- start: Delete vote modal -->
    <!-- Modal -->
    <div class="modal fade" id="delete-vote-modal" tabindex="-1" role="dialog" data-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Vote</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="voteId" id="voteId" value="" />
                    Do you want to delete this vote ?
                    <div style="text-align: center; display: none" id="loaderDiv">
                        <img src="~/images/loading.gif" width="150" />
                    </div>
                </div>
                <div class="modal-footer">
                  <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>              
                    <a class="btn btn-success" asp-action="DeleteVote" asp-controller="Discussion" asp-route-id="@Model.VoteId">Confirm</a>
                 
                </div>
            </div>
        </div>
    </div>

    And in the Controller for DeleteVote method

    [HttpGet]
            [Authorize(Policy = AuthPolicy.ELIGIBLE_TO_VOTE)]
            public async Task<IActionResult> DeleteVote(long id, CancellationToken cancellationToken)
            {
                try
                {
                    await _discussionService.DeleteVoteAsync(
                            id,
                            cancellationToken)
                        .ConfigureAwait(true);
                    //return RedirectToAction(nameof(Vote));
                  
                }
                catch
                {
                    Logger.LogError($"Error in deleting the Vote Id: {id}");
                   
                }
            }

    Tuesday, January 5, 2021 6:49 AM
  • User1686398519 posted

    Hi bootzilla, 

    1. Are you saying use the DeleteVotePost button to delete the vote that I should use a form to submit but it is better to use DeleteVoteGet?
      1. You have misunderstood what I meant.
      2. <a class="btn btn-success" asp-action="DeleteVoteGet" asp-controller="TestConfirm" asp-route-id="1">Confirm</a>
        1. If you want to send such a request, you need to note that the requested action should be the Get method, because <a> can only use the Get method.
          • In other words, <a> sends a Get request.
      3. [HttpPost]
        public async Task<IActionResult> DeleteVote(long id, CancellationToken cancellationToken)
        1. But the DeleteVote action you gave earlier is a POST method, so when you use <a> to send a request,it will fail.
        2. Therefore, I gave the second method, you can use the form to submit data, so you can request the DeleteVote action (Post method).
    2. When I debug it goes to the Vote post method in the controller instead of the DeleteVote method in the controller to delete the vote.
      • Have you specified the requested action and controller?
      • <form asp-controller="TestConfirm" asp-action="DeleteVote" method="post">

    Best Regards,

    YihuiSun

    Thursday, January 7, 2021 9:29 AM
  • User-501297529 posted

    YihuiSun

    Hi bootzilla, 

    1. bootzilla

      Are you saying use the DeleteVotePost button to delete the vote that I should use a form to submit but it is better to use DeleteVoteGet?
      1. You have misunderstood what I meant.
      2. <a class="btn btn-success" asp-action="DeleteVoteGet" asp-controller="TestConfirm" asp-route-id="1">Confirm</a>
        1. If you want to send such a request, you need to note that the requested action should be the Get method, because <a> can only use the Get method.
          • In other words, <a> sends a Get request.
      3. [HttpPost]
        public async Task<IActionResult> DeleteVote(long id, CancellationToken cancellationToken)
        1. But the DeleteVote action you gave earlier is a POST method, so when you use <a> to send a request,it will fail.
        2. Therefore, I gave the second method, you can use the form to submit data, so you can request the DeleteVote action (Post method).
    2. bootzilla

      When I debug it goes to the Vote post method in the controller instead of the DeleteVote method in the controller to delete the vote.
      • Have you specified the requested action and controller?
      • <form asp-controller="TestConfirm" asp-action="DeleteVote" method="post">

    Best Regards,

    YihuiSun

    As I said previously, this doesn't work. When I click the Delete button it doesn't delete anything, it just refreshes the page. 

    I ended up trying this and it seems to work by deleting the vote but I'm not sure how to redirect the view in the controller action, I have it with hard coded values at the moment:

    View

    <div class="card">
        <div class="card-body">
    
            @{
                if (@Model.PacketItemDetails != null)
                {
                    if (@Model.PacketItemDetails.PacketItemFileId != null
                        && @Model.PacketItemDetails.PacketItemFileId != 0)
                    {
                        <a asp-action="DownloadFile" class="orange"
                           target="_blank"
                           asp-controller="Asset"
                           asp-route-id="@Model.PacketItemDetails.PacketItemFileId ">
                            @Model.PacketItemDetails.Title
                        </a>
                    }
                    else
                    {
                        <div class="forum-orange">@Model.PacketItemDetails.Title</div>
                    }
    
                }
            }
    
            <p id="vote-status" class="card-text forum-blue">
    
                @{if (@Model.VoteId != 0)
                    {
                        <text>
                            <br />You have already voted on this item.
                            <br />Change by clicking Re-cast Vote or delete vote by clicking Delete Vote
                        </text>
                    }
                    else
                    {
                        <text><br />You have not voted on this item yet. Vote by selecting an option and clicking Vote.</text>
                    }
                }
            </p>
            @{
                if (Model.AvailableVotingOptions != null)
                {
                    @Html.DropDownListFor(m => m.VotingOptionId,
                        // 1. Store selected value in Model.VotingOptionId
                        // when page is rendered after postback,
                        // take selected value from Model.VotingOptionId.
    
                        // 2. Take list of values from Model.AvailableVotingOptions
                        Model.AvailableVotingOptions,
    
                        // 3. Text for the first 'default' option
                        "- Please select a vote -",
    
                        //4. A class name to assign to <select> tag
                        new { @class = "form-control", @id = "voting-options" })
                }
            }
            <div id="div-discuss-content" style="display: none">
                <br />
                <div class="control-label">Discuss Content</div>
                <textarea id="discuss-content" class="discuss-content" asp-for="Comments"></textarea>
            </div>
        </div>
        <div class="card-footer">
            <div class="row">
                <div class="col-sm-12 col-md-3 col-lg-3">
                    <button type="submit"
                            class="btn btn-success btn-sm col-sm-12"
                            id="vote-button"
                            data-action="submit">
                        <i class="fas fa-vote-yea fa-fw"></i>
                        @if (@Model.VoteId != 0)
                        {
                            <text>Re-Cast Vote</text>
                        }
                        else
                        {
                            <text>Vote</text>
                        }
    
                    </button>
                </div>
                    <div class="col-sm-12 col-md-3 col-lg-3">
                        <a data-toggle="modal"
                           id="delete-vote-button"
                           data-id="@Model.VoteId"
                           href="#delete-vote-modal"
                           class="btn btn-danger btn-sm delete-vote col-sm-12">
                            <i class="fa fa-trash fa-fw"
                               title="Delete"
                               style="color: white"></i>Delete Vote
                        </a>
                    </div>
                    <div class="col-sm-12 col-md-3 col-lg-3">
                        <button type="button"
                                class="btn btn-forum btn-sm col-sm-12"
                                id="back-to-packet">
                            <i class="fas fa-arrow-alt-circle-left fa-fw"></i>
                            Back To Packet
                        </button>
                    </div>
                </div>
        </div>
    </div>
    <!-- start: Delete vote modal -->
    <!-- Modal -->
    <div class="modal fade" id="delete-vote-modal" tabindex="-1" role="dialog" data-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Vote</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="voteId" id="voteId" value="" />
                    Do you want to delete this vote ?
                    <div style="text-align: center; display: none" id="loaderDiv">
                        <img src="~/images/loading.gif" width="150" />
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>
                    <button class="btn btn-success" id="confirm-delete-vote" type="button">Confirm</button>
                </div>
            </div>
        </div>
    </div>

    Js

     $(document).on("click",
            '#confirm-delete-vote',
            function (e) {
                var voteId = parseInt($(".modal-body #voteId").val());
                var packetItemId = $('#packet-item-id').val();
                var votingType = $('#voting-type').val();
    
                var data = {
                    id: voteId
                };
                location.href = '/Discussion/deletevote?id=' + voteId
    
            });

    Controller

     [HttpGet]
            [Authorize(Policy = AuthPolicy.ELIGIBLE_TO_VOTE)]
            public async Task<IActionResult> DeleteVote(long id, CancellationToken cancellationToken)
            {
                try
                {
                    await _discussionService.DeleteVoteAsync(
                            id,
                            cancellationToken)
                        .ConfigureAwait(true);
    
                    return Redirect("Vote?packetItemId=1&votingType='dsf13'");
                    //return Json(new { isSuccess = true, statusMessage = UserStringsService.VoteDeletedSuccessfully });
                }
                catch
                {
                    Logger.LogError($"Error in deleting the Vote Id: {id}");
                    return Json(new { isSuccess = false, statusMessage = UserStringsService.VoteDeleteFailed });
                }
            }

    Monday, January 11, 2021 8:18 PM
  • User475983607 posted

    I ended up trying this and it seems to work by deleting the vote but I'm not sure how to redirect the view in the controller action, I have it with hard coded values at the moment:

    Controller actions return an HTTP response.  In your sample code the DeleteVote() action returns a redirect (HTTP 302) not a View (200).  A standard HTTP redirect contains a location header that tells the browser where to make the next HTTP GET.   The browser simply follows the redirect.

    In the hardcoded redirect example, it is not clear where the URL parameters, packetItemId and votingType, come form. I assume the values would come form a database query or are passed to the DeleteVote() action.  

    Unfortunately, there's not much we can do to help you.  The logic you've shared is a very unique and it is difficult to understand the intent by reviewing the code.  Can you explain the general design and flow? 

    Monday, January 11, 2021 10:31 PM
  • User-501297529 posted

    mgebhard

    bootzilla

    I ended up trying this and it seems to work by deleting the vote but I'm not sure how to redirect the view in the controller action, I have it with hard coded values at the moment:

    Controller actions return an HTTP response.  In your sample code the DeleteVote() action returns a redirect (HTTP 302) not a View (200).  A standard HTTP redirect contains a location header that tells the browser where to make the next HTTP GET.   The browser simply follows the redirect.

    In the hardcoded redirect example, it is not clear where the URL parameters, packetItemId and votingType, come form. I assume the values would come form a database query or are passed to the DeleteVote() action.  

    Unfortunately, there's not much we can do to help you.  The logic you've shared is a very unique and it is difficult to understand the intent by reviewing the code.  Can you explain the general design and flow? 

    I'm trying to delete a vote that has been submitted. Packetitemid and votingtype are database values. They come from the view model. My question is should I return a redirect or a return a view? That's what I need help with. The example I'm using is a redirect but I'm not sure how to pass those values packetitemid and votingtype thru the redirect but that may not be the best way I don't know that's why I'm asking. Do you need to see the view model?

    Monday, January 11, 2021 10:56 PM
  • User475983607 posted

    Do you need to see the view model?

    the view model will not help.   The community needs to understand where the two URL parameters come from as explained in my first post.  According to the jQuery/JavaScript there are two HTML input elements, #packet-item-id and #voting-type, that contains these values but it is not clear what View renders these elements or how the inputs are populated. It seems to me the design needs to be simplified (refactored).

    Monday, January 11, 2021 11:40 PM
  • User-501297529 posted

    bootzilla

    Do you need to see the view model?

    the view model will not help.   The community needs to understand where the two URL parameters come from as explained in my first post.  According to the jQuery/JavaScript there are two HTML input elements, #packet-item-id and #voting-type, that contains these values but it is not clear what View renders these elements or how the inputs are populated. It seems to me the design needs to be simplified (refactored).

    It comes from this 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" />
                @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>
                }
                <partial name="_StatusMessage" for="@statusMessage" />
                <div id="add-edit-vote">
                    <partial name="_Vote" model="@Model" />
                </div>
            </div>
        </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>
    }

    The view in my original post is a partial view. This is the 'full' view, Does this help?

    Monday, January 11, 2021 11:54 PM
  • User475983607 posted

    Your response just confuses the design even further.  The two inputs, #packet-item-id and #voting-type, are not within a form so they are not submitted in a standard form post.  The JS code shared reads the two inputs when the #confirm-delete-vote input is clicked.  But the View shown in your most recent post does not have a #confirm-delete-vote input.  I'm not sure how to help you.  It seems you need to organize your thoughts before moving foreword. 

    Tuesday, January 12, 2021 12:22 AM
  • User-501297529 posted

    mgebhard

    Your response just confuses the design even further.  The two inputs, #packet-item-id and #voting-type, are not within a form so they are not submitted in a standard form post.  The JS code shared reads the two inputs when the #confirm-delete-vote input is clicked.  But the View shown in your most recent post does not have a #confirm-delete-vote input.  I'm not sure how to help you.  It seems you need to organize your thoughts before moving foreword. 

    #confirm-delete-vote input is in the partial view. I said the partial view code is in my original post. All the info on what code is where and why I need help is in my op and all throughout this thread.  Please stop with condescending me. You constantly do this. I'm asking for help, look at my original post you will see the code where the #confirm-delete-vote input is.

    Tuesday, January 12, 2021 12:30 AM
  • User-474980206 posted

    When the browser posts a form, it expect to display the response which is typically a new page. Your delete action probably should redirect to to the original  action passing any retired data on the query string the the server can recreate the html page without the item that was deleted.

    if you do a browser form post you can not do a partial page update, you server must recreate the complete page. Partial updates can only be done via Ajax.

    Tuesday, January 12, 2021 12:54 AM
  • User-501297529 posted

    When the browser posts a form, it expect to display the response which is typically a new page. Your delete action probably should redirect to to the original  action passing any retired data on the query string the the server can recreate the html page without the item that was deleted.

    if you do a browser form post you can not do a partial page update, you server must recreate the complete page. Partial updates can only be done via Ajax.

    So what does that redirect look like? Am I passing a redirect of Vote, DeleteVote? I just need to know what the redirect looks like. 

    Tuesday, January 12, 2021 1:07 AM