Home > OS >  Sending data from view to controller through ajax in asp.net
Sending data from view to controller through ajax in asp.net

Time:11-15

i create a add to favorite button by that i send the value of id of the button from view to controller through javascript and ajax in asp.net core mvc . But value of id always 1 even i click on another favorite button. Kindly tell me where i do mistake. My view:

 @foreach (var item in Model)
           {
 <div>
  <input id="houseid" type="hidden" value="@item.id">
  <a href="#"  id="favorite" onclick="favoritefunction()" >
</div>
}
<script>
                function favoritefunction() {
            var id = document.getElementById("houseid").value;
 debugger
            var xhttp = new XMLHttpRequest();
            
            xhttp.open("Get", "/Home/ajaxRent?id=" id, true);

           
            xhttp.send();
            alert("favorite added successfully");
}

    </script>

CodePudding user response:

Id should be unique,so each time the value of document.getElementById("houseid").value will find the same value.You can try to pass @item.id to favoritefunction.Here is a demo:

@foreach (var item in Model)
           {
 <div>
  <input id="houseid" type="hidden" value="@item.id">
  <a href="#"  id="favorite" onclick="favoritefunction(@item.id)" >a</a>
</div>
}
<script>
                function favoritefunction(id) {
           
            var xhttp = new XMLHttpRequest();
            
            xhttp.open("Get", "/Home/ajaxRent?id=" id, true);

           
            xhttp.send();
            alert("favorite added successfully");
}

    </script>
  • Related