1

I have looked around for a similar question, but all the answers don't work for my problem. I am creating a wishlist, and I want the link to only return some sort of confirmation, and not go to another view.

View:

...
    <div class="wishlist">
       @Html.ActionLink(" ", "AddToWishList", "Wishlist", routeValues: new
            {
               itm_id = item.id
            },
            htmlAttributes: new {@class = "heart" })
    </div>
...

Controller

 public async Task<ActionResult> AddToWishList(int itm_id, int recordId)
        {
            ...
            return RedirectToAction(nameof(Index));
        }
Floor
  • 216
  • 3
  • 16

2 Answers2

2

You want to use Ajax.ActionLink instead of Html.ActionLink. The article below should specify some of the details of the usage. Make sure you remember to include the jquery libraries or it will not generate the link type you are expecting.

https://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/ajax-actionlink-and-html-actionlink-in-mvc/

Personally, I would not use the Microsoft method and write a jQuery Ajax postback myself in JavaScript.

Brandon Barkley
  • 720
  • 6
  • 21
1

You can achieve this simply using Jquery Get. https://api.jquery.com/jquery.get/

This is your back end side.

public async Task<JsonResult> AddToWishList(int itm_id, int recordId)
        {
// Do you data here and put it to the List<something> list
            return Json(list, JsonRequestBehavior.AllowGet);
        }

and your front end should be something like this.

<button>Click</button>

<div class="wishlist">
</div>

<script>
$("button").click(function(){
$.get( "YourControllerName/AddToWishList",{itm_id: yourItemId, recordId: yourRecordId} function( data ) {
  $( ".wishlist" ).html( data );
  alert( "Load was performed." );
});
});
</script>
Mehmet Taha Meral
  • 3,315
  • 28
  • 30