locked
how to send selected row data from view to controller using ajax RRS feed

  • Question

  • User-1257308419 posted

    i have this List<ViewModel> through which i am populating a table so this table has many rows.
    what i want to do is to add a Button in every row and when that button is clicked i need to pass data from that row to my controller using ajax
    i can't seem to select values of single row and pass them to the controller using ajax this is what i am using
     

     <script>
                $('#captcha').on('click', function (e) {
              
        
                    var customer = {};
                    customer.U_ID = $("#some_property").val();
                    customer.P_ID = $("#some_property2").val();
        
                  //  customer.P_ID = row.find("TD").eq(1).html();
                    //Send the JSON array to Controller using AJAX.
                    $.ajax({
                        type: "POST",
                        url: "/Admin/AjaxDeleteMethod",
                        data: JSON.stringify(customer),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (r) {
                            alert(r + " record(s) inserted.");
                        }
                    });
                   
                });
                </script>

    only the first row button takes me to the controller and i only get the first row values.
    i need some way to send values of the rows of which button is clicked

    Thursday, September 10, 2020 8:54 PM

All replies

  • User475983607 posted

    Below is an example.  Unfortunately, you did not share the HTML which is the most important part...

    @model List<MvcBasic.Controllers.ItemViewModel>
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => Model[0].Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => Model[0].Quantity)
            </th>
            <th></th>
        </tr>
    
    @for (int i = 0; i < Model.Count(); i++) {
        <tr>
            <td>
                @Html.HiddenFor(modelItem => Model[i].Id)
                @Html.TextBoxFor(modelItem => Model[i].Name)
            </td>
            <td>
                @Html.TextBoxFor(modelItem => Model[i].Quantity)
            </td>
            <td>
                <button type="button" class="btn btn-primary">Save</button>
            </td>
        </tr>
    }
    
    </table>
    
    @section scripts{
        <script>
            $('.btn-primary').click(function (e) {
                var row = $(this).closest('tr');
    
                var data = {
                    Id: $(row).find('td input[name*="Id"]').val(),
                    Name: $(row).find('td input[name*="Name"]').val(),
                    Quantity: $(row).find('td input[name*="Quantity"]').val()
                };
    
                $.ajax({
                    type: "POST",
                    url: "/Ajax/Index",
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        console.log(response);
                    }
                });
            });
        </script>
    }
    namespace MvcBasic.Controllers
    {
        public class ItemViewModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Quantity { get; set; }
        }
        public class AjaxController : Controller
        {
            List<ItemViewModel> items;
            public AjaxController()
            {
                items = new List<ItemViewModel>()
                {
                    new ItemViewModel()
                    {
                        Id = 1,
                        Name = "Hello",
                        Quantity = 2
                    },
                    new ItemViewModel()
                    {
                        Id = 2,
                        Name = "World",
                        Quantity = 10
                    },
                    new ItemViewModel()
                    {
                        Id = 3,
                        Name = "Foo",
                        Quantity = 33
                    }
                };
            }
    
            // GET: Ajax
            [HttpGet]
            public ActionResult Index()
            {
                return View(items);
            }
    
            [HttpPost]
            public ActionResult Index(ItemViewModel Item)
            {
                return Json(Item);
            }
    
        }
    }

    Thursday, September 10, 2020 11:14 PM
  • User-1257308419 posted

    mgebhard

    var row = $(this).closest('tr');
    
                var data = {
                    Id: $(row).find('td input[name*="Id"]').val(),
                    Name: $(row).find('td input[name*="Name"]').val(),
                    Quantity: $(row).find('td input[name*="Quantity"]').val()
                };

    thanks but this didn't work for me it only gets the result from the first row if i click the button on its end but for second row the click does nothing

    this is the html

     @using (Html.BeginForm("ActivatePackages", "Admin"))
        {
            <div class="container-fluid">
                <!-- Basic Examples -->
                <div class="row clearfix">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <div class="card">
                            <div class="header">
                                <h2>
                                    <b>  Referential Users </b>
                                </h2>
    
                            </div>
                            <div class="body">
                                <div class="table-responsive">
                                    <table id="tblCustomers" class="table table-bordered table-striped table-hover js-basic-example dataTable">
                                        <thead>
                                            <tr>
                                                <th>User Name</th>
                                                <th>Package Name</th>
                                                <th>Amount</th>
                                                <th>Package Status</th>
                                                <th>Screenshot</th>
                                                <th>Transaction ID</th>
                                                <th>Deny</th>
    
                                            </tr>
                                        </thead>
                                        <tfoot>
                                            <tr>
                                                <th>User Name</th>
                                                <th>Package Name</th>
                                                <th>Amount</th>
                                                <th>Package Status</th>
                                                <th>Screenshot</th>
                                                <th>Transaction ID</th>
                                                <th>Deny</th>
    
                                            </tr>
                                        </tfoot>
                                        <tbody>
                                            @for (int i = 0; i < Model.Count; i++)
                                            {
                                                <tr>
                                                    <td >
                                                        @*@Html.Hidden("some_property2", Model[i].package.PID, new { @id = "some_property2" ,@class="nr" })*@
    
                                                        @Html.Hidden("some_property", Model[i].user.ID, new { @id = "some_property" })
                                                        @Html.Hidden("some_property2", Model[i].package.PID, new { @id = "some_property2" })
    
                                                        @Html.HiddenFor(modelItem => Model[i].user.ID)
                                                        @Html.HiddenFor(modelItem => Model[i].userPackage.U_ID)
                                                        @Html.HiddenFor(modelItem => Model[i].userPackage.P_ID)
                                                        @Html.DisplayFor(modelItem => Model[i].user.Name)
                                                    </td>
                                                    <td>
                                                        @Html.HiddenFor(modelItem => Model[i].package.PID)
                                                        @Html.DisplayFor(modelItem => Model[i].package.PName)
                                                    </td>
                                                    <td>
                                                        @Html.DisplayFor(modelItem => Model[i].transaction.Amount)
                                                    </td>
                                                    <td>
                                                        @Html.CheckBoxFor(modelitem => Model[i].userPackage.PackageStatus)
                                                    </td>
                                                    <td>
                                                        <a class="cancel" href="@Url.Action("ScreenShotDownload", "Admin", new { @id = Model[i].transaction.TransactionID })" title="Download">
    
                                                            <img src="@Url.Content(Model[i].transaction.ScreenShotPath)" />
                                                        </a>
                                                    </td>
                                                    <td>
                                                        @Html.DisplayFor(modelItem => Model[i].transaction.TransactionID)
                                                    </td>
                                                    <td>
                                                        @*<input id="delete" type="button" value="Delete" class="btn btn-outline-danger" />*@
                                                        @*<input type="button" onclick="ajaxFunc();" class="btn btn-outline-danger" id="captcha" value="Verify" />*@
                                                        @*<input type="button" class="btn btn-outline-danger" id="captcha" value="Delete!" />*@
                                                        <input type="button" class="btn btn-outline-danger" id="captcha" value="Delete!" />
    
                                                    </td>
                                                </tr>
                                            }
    
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- #END# Basic Examples -->
                <!-- Exportable Table -->
    
            </div>
            <input type="submit" value="Approve" class="btn btn-outline-success" />
    
        }

    i need to do two things first if button is clicked on the end of the row then pas this data via ajax to controller and do something and then there's a form submit too for sending remaining rows to the controller.

    what i really am trying to do is to delete a record if clicked on and then submit the remaining rows 

    EDIT:-

    your solution also works 100% fine appparently there's some issue with using ID instead of class because i was using ID value using # tag on click

    it was working only for the firs row as soon as i changed it to class it started working for every row click.

    but there's some weird issue...packagestatus value coming in ajaxdeletemethod is true while it should be false...can't figure out why its showing true instead of false

    Friday, September 11, 2020 1:27 AM
  • User1686398519 posted

    Hi Learner94,

    According to your needs, I modified your code, you can refer to it.

    1. I am not connected to the database, you can modify the code for deletion and query according to your needs.
    2. You need to create a model called CustomerViewModel to receive the object sent by Ajax.

    More details, you could refer to below code:

    Model

        public class TestViewModel
        {
            public UserTestModel user{ get; set; }
            public PackageTestModel package { get; set; }
            public UserPackageTestModel userPackage { get; set; }
            public TransactionTestModel transaction { get; set; }
        }
        public class CustomerViewModel
        {
            public int U_ID { get; set; }
            public int P_ID { get; set; }
            public int ID { get; set; }
            public int PID { get; set; }
            public string Name { get; set; }
            public string Amount { get; set; }
            public bool PackageStatus { get; set; }
            public string ScreenShotPath { get; set; }
            public int TransactionID { get; set; }
        }
        public class UserTestModel
        {
            [Key]
            public int ID { get; set; }
            public string Name { get; set; }
        }
        public class PackageTestModel
        {
            [Key]
            public int PID { get; set; }
            public string PName { get; set; }
        }
        public class UserPackageTestModel
        {
            [Key]
            public int U_ID { get; set; }
            public int P_ID { get; set; }
            public bool PackageStatus { get; set; }
        }
        public class TransactionTestModel
        {
            [Key]
            public int TransactionID { get; set; }
            public string ScreenShotPath { get; set; }
            public string Amount { get; set; }
        }

    Controller

        public class UserTestController : Controller
        {
            public static List<TestViewModel> testlist = new List<TestViewModel> {
                new TestViewModel {
                        user= new UserTestModel { ID = 1, Name = "Name1" },
                        package= new PackageTestModel { PID = 1, PName = "PName1" },
                        userPackage= new UserPackageTestModel { P_ID =1, U_ID = 1, PackageStatus = true },
                        transaction= new TransactionTestModel { TransactionID = 1, Amount = "Amount1", ScreenShotPath = "~/Files/1.png" }
                },
                new TestViewModel {
                        user= new UserTestModel { ID = 2, Name = "Name2" },
                        package= new PackageTestModel { PID = 1, PName = "PName2" },
                        userPackage= new UserPackageTestModel { P_ID =2, U_ID = 2, PackageStatus = false },
                        transaction= new TransactionTestModel { TransactionID = 2, Amount = "Amount2", ScreenShotPath = "~/Files/1.png" }
                },
                new TestViewModel {
                        user= new UserTestModel { ID = 3, Name = "Name3" },
                        package= new PackageTestModel { PID = 1, PName = "PName3" },
                        userPackage= new UserPackageTestModel { P_ID =3, U_ID = 3, PackageStatus = true },
                        transaction= new TransactionTestModel { TransactionID = 3, Amount = "Amount3", ScreenShotPath = "~/Files/1.png" }
                }
            };
            public ActionResult Index()
            {
                return View(testlist);
            }
            [HttpPost]
            public ActionResult AjaxDeleteMethod(CustomerViewModel customer)
            {
                //do something to delete
                var testViewModel = new TestViewModel();
                testlist.ForEach(t => { if (t.user.ID == customer.ID) { testViewModel = t; } });
                testlist.Remove(testViewModel);
                return Json(customer,JsonRequestBehavior.AllowGet);
            }
            [HttpPost]
            public ActionResult ActivatePackages(List<TestViewModel> test)
            {
                //do something
                return RedirectToAction("Index");
            }
        }

    View

    @using (Html.BeginForm("ActivatePackages", "Usertest",FormMethod.Post))
    {
        <div class="container-fluid">
            <div class="row clearfix">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <div class="card">
                        <div class="header">
                            <h2>
                                <b>  Referential Users </b>
                            </h2>
    
                        </div>
                        <div class="body">
                            <div class="table-responsive">
                                <table id="tblCustomers" class="table table-bordered table-striped table-hover js-basic-example dataTable">
                                    <thead>
                                        <tr>
                                            <th>User Name</th>
                                            <th>Package Name</th>
                                            <th>Amount</th>
                                            <th>Package Status</th>
                                            <th>Screenshot</th>
                                            <th>Transaction ID</th>
                                            <th>Deny</th>
    
                                        </tr>
                                    </thead>
                                    <tfoot>
                                        <tr>
                                            <th>User Name</th>
                                            <th>Package Name</th>
                                            <th>Amount</th>
                                            <th>Package Status</th>
                                            <th>Screenshot</th>
                                            <th>Transaction ID</th>
                                            <th>Deny</th>
    
                                        </tr>
                                    </tfoot>
                                    <tbody>
                                        @for (int i = 0; i < Model.Count; i++)
                                        {
                                            <tr>
                                                <td>
                                                    @Html.Hidden("some_property", Model[i].user.ID, new { @id = "some_property" })
                                                    @Html.Hidden("some_property2", Model[i].package.PID, new { @id = "some_property2" })
                                                    @Html.HiddenFor(modelItem => Model[i].user.ID)
                                                    @Html.HiddenFor(modelItem => Model[i].userPackage.U_ID)
                                                    @Html.HiddenFor(modelItem => Model[i].userPackage.P_ID)
                                                    @Html.HiddenFor(modelItem => Model[i].user.Name)
                                                    @Html.DisplayFor(modelItem => Model[i].user.Name)
                                                </td>
                                                <td>
                                                    @Html.HiddenFor(modelItem => Model[i].package.PID)
                                                    @Html.DisplayFor(modelItem => Model[i].package.PName)
                                                    @Html.HiddenFor(modelItem => Model[i].package.PName)
                                                </td>
                                                <td>
                                                    @Html.DisplayFor(modelItem => Model[i].transaction.Amount)
                                                    @Html.HiddenFor(modelItem => Model[i].transaction.Amount)
                                                </td>
                                                <td>
                                                    @Html.CheckBoxFor(modelitem => Model[i].userPackage.PackageStatus)
                                                </td>
                                                <td>
                                                    @Html.HiddenFor(modelItem => Model[i].transaction.ScreenShotPath)
                                                    <a class="cancel" href="@Url.Action("ScreenShotDownload", "Admin", new { @id = Model[i].transaction.TransactionID })" title="Download">
    
                                                        <img src="@Url.Content(Model[i].transaction.ScreenShotPath)" />
                                                    </a>
                                                </td>
                                                <td>
                                                    @Html.DisplayFor(modelItem => Model[i].transaction.TransactionID)
                                                    @Html.HiddenFor(modelItem => Model[i].transaction.TransactionID)
                                                </td>
                                                <td>
                                                    <input type="button" class="btn btn-outline-danger captcha" value="Delete!" />
                                                </td>
                                            </tr>
                                        }
    
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <input type="submit" value="Approve" class="btn btn-outline-success" />
    }
    @section scripts{
        <script>
            $('.captcha').on('click', function (e) {
                var $tr = $(this).closest("tr")   // Finds the closest row <tr>
                var customer = {};
                customer.ID = $tr.find('td input[name*="user.ID"]').val();
                customer.PID = $tr.find('td input[name*="PID"]').val();
                customer.Name = $tr.find('td').eq(0).text().trim();
                customer.Amount = $tr.find('td').eq(2).text().trim();  
                customer.PackageStatus = $tr.find('td input[name*="PackageStatus"]').val();
                customer.ScreenShotPath = $tr.find('td img').attr('src');
                customer.TransactionID = $tr.find('td').eq(5).text().trim();  
                customer.U_ID = $tr.find('td input[name*="U_ID"]').val(); 
                customer.P_ID = $tr.find('td input[name*="P_ID"]').val();
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("AjaxDeleteMethod")",
                    data: JSON.stringify(customer),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        window.location.href = "Index";
                    }
                });
            });
        </script>
    }

    Here is the result.

    Best Regards,

    YihuiSun

    Friday, September 11, 2020 6:14 AM
  • User-1257308419 posted

    YihuiSun

    var $tr = $(this).closest("tr")   // Finds the closest row <tr>
                var customer = {};
                customer.ID = $tr.find('td input[name*="user.ID"]').val();
                customer.PID = $tr.find('td input[name*="PID"]').val();
                customer.Name = $tr.find('td').eq(0).text().trim();
                customer.Amount = $tr.find('td').eq(2).text().trim();
                customer.PackageStatus = $tr.find('td input[name*="PackageStatus"]').val();
                customer.ScreenShotPath = $tr.find('td img').attr('src');
                customer.TransactionID = $tr.find('td').eq(5).text().trim();
                customer.U_ID = $tr.find('td input[name*="U_ID"]').val();
                customer.P_ID = $tr.find('td input[name*="P_ID"]').val();

    thanks for so much effort but this works only for the first row..nothing happens if i click on anyother row delete  button

    EDIT:-

    click is working now i think issue was that i was using button i changed it to input type=button and changed id=captcha to class=captcha

    but now issue is that in controller when i have a simple model then it gets value fine for it(for eg if  i use UserPackage model then it gets value fine)...but when i try to pass view model it show null for user,packages,transaction,userpackages 

    EDIT-2:-

    your code works 100% fine i created a new model to get ll values from ajax to AjaxDeleteMethod but is there any way i can pass PendingPaymentApprovals model same one which i populating the table rows in the view?

    public class PendingPaymentApprovalsModel
        {
         public  User user { get; set; }
    
            public UserPackage userPackage { get; set; }
    
            public Transaction transaction { get; set; }
    
            public Package package { get; set; }
        }

    and then access in AjaxDeleteMethod with transaction.transactionID,UserPackages.U_ID etc?
     also package status is not showing correct value it shows true when it should be false and this remains the same whether checkbox value is checked or not but i think thats because its getting value from the model which is getting value from database and not from the currently selected checkbox value 

    Friday, September 11, 2020 6:29 AM
  • User1686398519 posted

    Hi Learner94, 

    1. hen access in AjaxDeleteMethod with transaction.transactionID,UserPackages.U_ID etc?
      • Because you are using ajax to send an object called consumer, not the PendingPaymentApprovalsModel. Therefore, UserPackages.U_ID cannot be used to get the value like this.
    2. checked or not but i think thats because its getting value from the model
      • According to what you mean here, the checkbox cannot be modified. You can modify the code like this.
        • @Html.CheckBoxFor(modelitem => Model[i].userPackage.PackageStatus, new { @disabled = "disabled" })

    Best Regards,

    YihuiSun

    Tuesday, September 15, 2020 8:27 AM