I am trying to find a way to send the id of the clicked button to the backend. The problem is that I am creating lots of buttons with one method but the id is different.
@foreach (var item in Model.showManager.GetMovies())
{
i ;
@if (Model.user.IsAdmin == true)
{
<input type="submit" id=i value="Delete"/>
}
}
The point is that every button is created with different id and I want to send that id to the backend.
CodePudding user response:
Refer to the below code, change your id=i
into id=@i
@for (var i = 0; i < 5;i )
{
<input type="submit" id=@i value="Delete" />
}
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(".btn_confirm").click(function()
{
var data = (this).id;
$.ajax({
type: "POST",
url: '/DynamicButton/Index/',
data: { id: data }
});
});
CodePudding user response:
The point is that every button is created with different id and I want to send that id to the backend.
Well, based on your issue, you want to bind all the button ids
then want to pass those Ids
in your backend.
However, another answer has guided you how to pass id to your controller
nonetheless, it doesn't resolve your main concern that is how to pass the list of ids
on button submit.
Algorithm:
As said earlier, first you have to get the list of button ids
which has been generated from your foreach loop
and you have to push them in an array[]
, finally need to pass those in your controller (backend)
. Here, importantly you have to keep in mind, it doesn't matter how the button been generated, for loop
or foreach loop
the fact is your button should have class name of same type
and the ids
for instance: and
id="btnId:@i"
Solution:
View:
@{
ViewData["Title"] = "ViewGetDynamicButtonsID";
}
<div>
@for (var i = 1; i < 5; i )
{
<input id="btnId:@i" value="Delete:@i" style="margin-bottom:2px" /> <br />
}
<input type="submit" id="btnSubmit" value="Submit" />
</div>
@section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSubmit").on("click", function () {
var ids = [];
$(".myBtnClass").each(function () {
//Getting All Button Ids and Pusing in array
ids.push($(this).attr("id"));
});
$.ajax({
type: "POST",
url: 'http://localhost:5094/stuff/GetAllButtonId',
datatype: "json",
data: { buttonids: ids },
success: function (res) {
console.log(res);
alert("It works")
},
error: function () {
alert("It failed");
}
});
return false;
});
});
</script>
}
Controller:
public IActionResult CreateDynamicButton()// This is for loading the view
{
return View();
}
[HttpPost]
public IActionResult GetAllButtonId(List<string> buttonids) // This for submit the button request.
{
return Ok(buttonids);
}
Output:
I hope this is what exactly you wanted.