简体   繁体   中英

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

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="#" class="phone_number" 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>

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="#" class="phone_number" 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM