Toast with foreach loop

1.6k views Asked by At

I hope that somebody know how to solve my problem. So, I have installed Toastr to show notifications in my ASP.NET MVC application. And what I have is the view with table and foreach loop for every element passed from controller:

@foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.CategoryName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.StartDate)
            </td>
            <td>
               @{
                    Html.RenderAction("_CourseQuantityCount", "Course", new { item.CourseID });
                }
                /@Html.DisplayFor(modelItem => item.MaximumQuantity)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td id="alert">
                @Html.ActionLink("SignIn", "SignIntoCourse", new { item.CourseID }, new { id = "myLink" })
            </td>
        </tr>
                    }
</table>

After the view there is a script section which look like this:

@section scripts {  

<script type="text/javascript">
        $(document).ready(function () {
            toastr.options = {
                "closeButton": false,
                "debug": false,
                "newestOnTop": false,
                "progressBar": false,
                "positionClass": "toast-top-center",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": "5000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"

            };
            $('#alert').click(function () {
                toastr.warning('Already signed!')
            });
        });

        $('#myLink').click(function (e) {

            e.preventDefault();
            $.ajax({
                url: $(this).attr("href"),
            });

        });
        </script>
}

And finally if I load my app it works good, but only for the first element from foreach loop. The aim is that if a user is signed into a course he received a toast that he is signed already. I think that the problem can be the same id within all foreach loop, but I am not sure. And I don't know how to create multiple ids and then use it in JS scripts in a way without refreshing a page, but only receiving toast.

1

There are 1 answers

0
Shyju On BEST ANSWER

Your current code is generating markup with more than one anchor tag with same Id(myLink). That is not valid HTML markup. Your Id's should be unique.

What you can do is, to give a css class and use that as the jQuery selector for wiring up the click event.

<td>
   @Html.ActionLink("SignIn", "SignIntoCourse", new { courseId= item.CourseID }, 
                                                          new { class = "myLink" })
</td>

Now listen to the click event of element with css class

$(function(){

   $("a.myLink").click(function(e){
      e.preventDefault();
      //do something here, may be make an ajax call.
   });

});

Now you can write code to make an ajax call to the server method which does something and return a response. Assuming your SignIntoCourse action method returns a response like this.

[HttpPost]
public ActionResult SignIntoCourse(int courseId)
{
   //do your code to check and return either one of the response
   if(alreadySignedUp)  // your condition here
   {
     return Json(new { status="failed",message = "Already Signed into course" });
   }
   else
   {
     return Json(new { status="success",message = "Signed into course" });
   }      
}

Now in your ajax' call's success callback, you simply check the json data's status property value and do whatever you have to.

$(function(){

   $("a.myLink").click(function(e){
      e.preventDefault();
      var url=$(this).attr("href");
      $.post(url,function(data){
         if(data.status==="success")
         {
           toastr.success(data.message, 'Success');
         }
         else
         {
           toastr.warning(data.message, 'Warning');
         }
      });
   });

});