locked
How to pass a dynamic Id from table to modal RRS feed

  • Question

  • User991566988 posted

    Hi

    I'm trying to pass a master dynamic id to a modal to retrieve detail data by Ajax, but always the first Id is passed for all records not the current.

     The method of getting detail data:

            public IActionResult Get(int? id)
            {
                var countriesTr = (from c in _context.CountriesTr
                                   where c.CountryID == id
                                  select c).FirstOrDefault();
                return new JsonResult(countriesTr);
            }

    Countries/Index view:

    @model IEnumerable<Countries>
    
    <table class="table">
        <thead>
            <tr>
                <th></th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
            <tr>         
                <td>
                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#AjaxMod" id="Modal" data-mas-id="@item.Id">
                        Translation
                    </button>
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
            </tr>
            }
        </tbody>
    </table>
    <div class="modal fade" id="AjaxMod" tabindex="-1" role="dialog" aria-labelledby="addContactLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content mod">
                <div class="modal-header">
                    <h5 class="modal-title" id="addContactLabel">Translation</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="save">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <input type="text" class="form-control" id="masid" name="mas-id" />
                                    <input type="text" class="form-control" id="detid" />                               
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <div>
                                        <label>Name</label>
                                        <input type="text" id="co" class="form-control" dir="ltr" />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save</button>
                        </div>
                    </form>
                </div>
    
            </div>
        </div>
    </div>
    
    
    @section Scripts {
        <script>
            $(document).ready(function () {
                $(function () {
                    $('#Modal').click(function () {
                        $("#AjaxMod").find("#masid").val($(this).data("mas-id"));
                        var options = {};
                        var cid = $('#masid').val();
                        options.url = "/CountriesTr/Get?id=" + cid,
                        options.type = "GET";
                        options.dataType = "json";
                        options.success = function (data) {
                            $("#detid").val(data.id);
                        };
                        options.error = function () {
                            $("#msg").html("Error while making Ajax call!");
                        };
                        $.ajax(options);
                    });
                });
            });
    
        </script>
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

    But when I press the modal button, The first Id always is passed not the current.

    How to pass the current master Id to the modal please?

    Saturday, July 25, 2020 5:56 PM

Answers

  • User-17257777 posted

    Hi Musbah,

    If you use id selector, the id should be unique, while the Translation button is in a foreach loop, so they will have the same id "Modal".

    In this case, you had better use name selector, add a name attribute to the button, change it like below:

    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#AjaxMod" name="Modal" id="Modal" data-mas-id="@item.Id">
                            Translation
                        </button>
    @section Scripts {
        <script>
            $(document).ready(function () {
                $(function () {
                    $('[name = Modal]').click(function () {
                        $("#AjaxMod").find("#masid").val($(this).data("mas-id"));
                        var options = {};
                        var cid = $('#masid').val();
                        options.url = "/CountriesTr/Get?id=" + cid,
                        options.type = "GET";
                        options.dataType = "json";
                        options.success = function (data) {
                            $("#detid").val(data.id);
                        };
                        options.error = function () {
                            $("#msg").html("Error while making Ajax call!");
                        };
                        $.ajax(options);
                    });
                });
            });
    
        </script>
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 28, 2020 7:34 AM

All replies

  • User475983607 posted

    There are a lot of potential problems with the code.  The first step is taking advantage of the rich debugging tools that come with Visual Studio and browsers.   I feel someone with your experience on the forum should make solid attempt to debug and clean up the code.

    I assume the #masid selector returns nothing.  At least, there's indication that the #masid is ever populated.  Use the browser's dev tools to see the value of cid.

    var cid = $('#masid').val();
    console.log(cid); options.url = "/CountriesTr/Get?id=" + cid,

    From there the rest of the dominos fall. The Get() action allows a null "id" parameter and the LINQ query returns a default type without checking if the query was successful or not.  IMHO the code should be tightened up.   

    Take a few second to set a Visual Studio break point and check parameters.  Is the id null?  Are the properties of countriesTr what you expect?  BTW, you can also see the response in the browser's dev tools.

            public IActionResult Get(int? id)
            {
                var countriesTr = (from c in _context.CountriesTr
                                   where c.CountryID == id
                                  select c).FirstOrDefault();
                return new JsonResult(countriesTr);
            }

    I think you are attempting to the Bootstrap vary content pattern but you are not following the JavaScript pattern correctly.

    https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content

    Anyway, use the debugger and clean up your code a bit.

    Saturday, July 25, 2020 8:06 PM
  • User-17257777 posted

    Hi Musbah,

    If you use id selector, the id should be unique, while the Translation button is in a foreach loop, so they will have the same id "Modal".

    In this case, you had better use name selector, add a name attribute to the button, change it like below:

    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#AjaxMod" name="Modal" id="Modal" data-mas-id="@item.Id">
                            Translation
                        </button>
    @section Scripts {
        <script>
            $(document).ready(function () {
                $(function () {
                    $('[name = Modal]').click(function () {
                        $("#AjaxMod").find("#masid").val($(this).data("mas-id"));
                        var options = {};
                        var cid = $('#masid').val();
                        options.url = "/CountriesTr/Get?id=" + cid,
                        options.type = "GET";
                        options.dataType = "json";
                        options.success = function (data) {
                            $("#detid").val(data.id);
                        };
                        options.error = function () {
                            $("#msg").html("Error while making Ajax call!");
                        };
                        $.ajax(options);
                    });
                });
            });
    
        </script>
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 28, 2020 7:34 AM
  • User991566988 posted

    you are right!

    Thanks

    Saturday, August 8, 2020 11:56 AM