Foreach button click ajax help

Nick R 66 Reputation points
2023-03-01T21:32:48.6833333+00:00

Good day everyone!

For some silly reason, I'm having a brain fart and can't remember how to add data to table when clicking on a button inside of a foreach loop.

I have added some code below:

I do get the id passing to item but I don't think it's being passed to my controller?

Any help would be greatly appreciated, thank you!

foreach (var item in Model.Events)
{
   <div class="col-md-3 mb-3">
      <div class="card">
         <div class="footer">
            <a onclick="saveEntry(@item.Id)" class="btn btn-secondary w-100">Enter Event</a>
         </div>
      </div>
   </div>
}

<script>
   function saveEntry(item) {
      var id = item;

      $.ajax({
         type: 'POST',
         data: JSON.stringify(id),
         url: '@Url.Action("SaveEntry", "Contest")',
         contentType: 'json',
         success: function (r) {
            alert(r);
         },
         error: function () {
            alert('Something went wrong. Please refresh the page and try again.');
         }
      });
   }
</script>

[HttpPost]
public virtual IActionResult SaveEntry(int item)
{
   //save current user into table called Entry
   return Json(new
   {
      status = true,
      msg = "You have successfully entered this event."
   });
}
Developer technologies | .NET | Entity Framework Core
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-03-02T07:24:28.7066667+00:00

    Hi @Nick R

    Try to modify your code as below:

    <script>
       function saveEntry(value) {
          var id = value;
    
          $.ajax({
             type: 'POST',
             data: { item : id },
             url: '@Url.Action("SaveEntry", "Contest")', 
             contentType: 'json',
             success: function (r) {
                alert(r);
             },
             error: function () {
                alert('Something went wrong. Please refresh the page and try again.');
             }
          });
       }
    </script>
    

    The result as below:

    image1


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. SurferOnWww 4,711 Reputation points
    2023-03-02T00:26:25.2366667+00:00

    Please try:

    <script>
       function saveEntry(item) {
          $.ajax({
             type: 'POST',
             data: JSON.stringify(id),
             url: '@Url.Action("SaveEntry", "Contest")' + '?item=' + item,
             success: function (r) {
                alert(r);
             },
             error: function () {
                alert('Something went wrong. Please refresh the page and try again.');
             }
          });
       }
    </script>
    

    or

    <script>
       function saveEntry(id) {
          var data = { item: id } ;
    
          $.ajax({
             type: 'POST',
             data: JSON.stringify(data),
             url: '@Url.Action("SaveEntry", "Contest")',
             contentType: "application/json; charset=utf-8",
             success: function (r) {
                alert(r);
             },
             error: function () {
                alert('Something went wrong. Please refresh the page and try again.');
             }
          });
       }
    </script>
    

  2. AgaveJoe 30,126 Reputation points
    2023-03-02T16:35:06.9066667+00:00

    You have to keep in mind that we cannot see the data. when asking for assistance try to provide sample code the community can actually run. Below is a working example using mock data. The success message is written to the browser's dev tools console (F12).

    @model MvcDemo.Models.EventVm
    
    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    
    
    @foreach (var item in Model.Events)
    {
        <div class="col-md-3 mb-3">
            <div class="card">
                <div class="footer">
                    <a onclick="saveEntry(@item.Id)" class="btn btn-secondary w-100">Enter Event</a>
                </div>
            </div>
        </div>
    }
    <div id="error-message"></div>
    
    @section Scripts {
        <script>
            function saveEntry(id) {
                $.ajax({
                    type: 'POST',
                    data: {},
                    url: '@Url.Action("SaveEntry", "Contest")/' + id,
                    contentType: 'json',
                    success: function (r) {
                        console.log(r);
                    },
                    error: function () {
                        document.getElementById('error-message').innerHTML('Something went wrong. Please refresh the page and try again.')
                    }
                });
            }
        </script>
    }
    

    Action

        public class ContestController : Controller
        {
           
            public IActionResult Index()
            {
                EventVm vm = new EventVm()
                {
                    Events = new List<Event>()
                    {
                        new Event() { Id = 1},
                        new Event() { Id = 2},
                        new Event() { Id = 3}
                    }
                };
                return View(vm);
            }
    
            [HttpPost]
            public virtual IActionResult SaveEntry(int id)
            {
                //save current user into table called Entry
                return Json(new
                {
                    id,
                    status = true,
                    msg = "You have successfully entered this event."
                });
            }
        }
    

    A couple of items to note. Since your sending an Id you can just use a route parameter, as I did, or a query string (url). There's no need to serialize the unless you are working with a complex type.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.