locked
how to show popup with list returned by ajax result set and how to select item and return it back to parent html RRS feed

  • Question

  • User1094269964 posted

    HI Team,

    I am trying to show a model dialog or popup to show list of users returned by ajax call to Controller Action. In the model dialog or popup where use can select a particular user and then  I want to show the selected User details in this same view

    But  I am struggling to develop a code to show popup or model dialog to show list of users and select any of the user and show the selected user details.

    Please help

    Below is my sample code which I am working now

    Below is my C# code 

    public class UserDetail
    {
    public string UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    }

    -----------------

    public class DemoController:Controller

    {

    <div> [HttpPost]</div> <div>        public JsonResult Search(string strUser)</div> <div>        {</div> <div>            List<UserDetail> users = new List<UserDetail>();</div> <div>            for (int i = 0; i < 5; i++)</div> <div>            {</div> <div>                UserDetail user = new UserDetail();</div> <div>                user.UserId = "UserID_" + i.ToString();</div> <div>                user.UserName = "User" + i.ToString();</div> <div>                user.Email = "Email" + i.ToString() + "@test.com";</div> <div>                user.Phone = "111" + i.ToString();</div> <div>                users.Add(user);</div> <div>            }</div> <div>            return this.Json(users);</div> <div> </div> <div>        }</div>

    }

    ----------------------

    ASP.NET MVC VIew

    <div> </div> <div>@{</div> <div>    ViewBag.Title = "Index";</div> <div>}</div> <div> </div> <div> </div> <div><h2>This is from Demo Index</h2></div> <div> </div> <div><div></div> <div>    <input type="text" id="txtFname"/></div> <div>    <button class="btn btn-xs" id="btnSearch"></div> <div>        <span>SearchByFirstName</span></div> <div>    </button></div> <div></div></div> <div> </div> <div><div></div> <div>    <p>Show selected User Details</p></div> <div></div></div> <div> </div> <div>@section scripts</div> <div></div> <div>    <script></div> <div>        $("#btnSearch").click(function (e) {           </div> <div>            $.ajax({</div> <div>                type:"POST",</div> <div>                dataType: 'json',</div> <div>                url: "/Demo/SearchByFirstName",</div> <div>                data: {</div> <div>                    strUser: $("#txtFname").val() },</div> <div>                success: function (result) {</div> <div>                   //Here I want to show a popup with list of users retuned by the ajax result</div> <div>                   //In the popup user can select any of the user</div> <div>                    //After that here I can make another ajax call</div> <div>                },</div> <div>                error: function (XMLHttpRequest, textStatus, errorThrown) {</div> <div>                    debugger;</div> <div> </div> <div>                }</div> <div>            });</div> <div>        })</div> <div>    </script></div> <div> </div> <div>}</div>

    Thursday, July 2, 2020 11:15 AM

Answers

  • User-939850651 posted

    Hi bsurendiran,

    You could pass the data in each user record to the js method, and then do what you want to the operation.

    Just like this:

    $("#btnSearch").click(function (e) {
                $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "/Demo/SearchByFirstName",
                    data: {
                        strUser: $("#txtFname").val()
                    },
                    success: function (result) {
                        $("#modalTable").html("");
                        var tr = "<tr><th>Action</th><th>UserId</th><th>UserName</th><th>Email</th><th>Phone</th></tr>"
                        $("#modalTable").append(tr);
                        for (var user of result) {
                            tr = "<tr><td><button type=\"button\" onclick=\"myFunction('" + user.UserId + "')\" class=\"btn btnSelect\">Select</button></td><td>" + user.UserId + "</td><td>" +
                                user.UserName + "</td><td>" + user.Email +
                                "</td><td>" + user.Phone + "</td></tr>"
    
                            $("#modalTable").append(tr);
                        }
                        $('#myModal').modal('show');
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        debugger;
                        alert("Content load failed.");
                    }
                });
            });
    
            function myFunction(userId) {
                alert("UserId==>" + userId);
                //do something here
            }

    Result:

    Best regards,

    Xudong Peng 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 15, 2020 10:09 AM
  • User348806598 posted

    Hi,

    You can do without passing complete object. In the button click, myFunction, event you can try this code-

    var containerRow = $(this).closest('tr');
    
    var userId =containerRow.find("td:nth-child(2)");
    var userName =containerRow.find("td:nth-child(3)");
    var userEmail =containerRow.find("td:nth-child(4)");
    var phone =containerRow.find("td:nth-child(5)");
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 16, 2020 3:44 AM

All replies

  • User-939850651 posted

    Hi bsurendiran,

    If you want to display the data of these queries in a modal popup, you can manually fill in the content.

    Just like this:

    $("#btnSearch").click(function (e) {
                $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "/Demo/SearchByFirstName",
                    data: {
                        strUser: $("#txtFname").val()
                    },
                    success: function (result) {
    $("#modalTable").html(""); var tr = "<tr><th>UserId</th><th>UserName</th><th>Email</th><th>Phone</th></tr>" $("#modalTable").append(tr); for (var user of result) { tr = "<tr><th>" + user.UserId + "</th><th>" + user.UserName + "</th><th>" + user.Email + "</th><th>" + user.Phone + "</th></tr>" $("#modalTable").append(tr); } $('#myModal').modal('show'); }, error: function (XMLHttpRequest, textStatus, errorThrown) { debugger; alert("Content load failed."); } }); });

    Or I found some cases similar to your needs, you could refer to them.

    https://www.aspsnippets.com/Articles/Implement-and-display-jQuery-Modal-Popup-Dialog-Window-in-ASPNet-MVC-Razor.aspx

    https://www.c-sharpcorner.com/article/render-partial-view-as-modal-popup-using-ajax-call-with-json/

    Best regards,

    Xudong Peng

    Friday, July 3, 2020 8:57 AM
  • User348806598 posted

    You can use fancybox with ajax-

    @{
        ViewBag.Title = "Home Page";
        Layout = "~/Pages/Shared/_Layout.cshtml";
    }
    
    <h2>Index</h2>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.css" media="screen" />
    
    <a id="fancy" href="#users">Show data</a>
    <div id="users" style="display:none">
        <table>
            <thead ><tr id="tblHead"></tr></thead>
            <tbody id="tblBody">
            </tbody>
        </table>
    </div>
    <div id="selectedData" style="display:none">
        <div>User id: <label id="userId"></label></div>
        <div>User name: <label id="userName"></label></div>
        <div>Email: <label id="email"></label></div>
        <div>Phone: <label id="phone"></label></div>
    </div>
    <script>
        var users = [];
        function selectUser(i) {
            var user = users[i];
            for (var key in user) {
                $('#'+key).html(user[key]);
            }
            $("#selectedData").show();
        }
        $.ajax({
            url:  '@Url.Action("GetUsers", "_2168647_how_to_show_popup_with_list_returned_by_ajax_result_set_and_how_to_select_item_and_return_it_back_to_parent_html")',
            data: {  },
            type: "GET",
            success: function (response) {
                var tableBody = $("#tblBody");
                $.map(response, function (item, i) {
                    users = response;
                    if (i == 0) {
                        var thead = $("#tblHead");
                        for (var key in item) {
                            $('<th>').html(key).appendTo(thead);
                        }
                    }
                    var row = $('<tr>');
                    for (var key in item) {
                        $('<td>').html(item[key]).appendTo(row);
                    }
                    $('<td>').html('<a onclick="selectUser(' + i +');$.fancybox.close();">Select user</a>').appendTo(row);
                    row.appendTo(tableBody);
                })
                console.table(response);
                $("#fancy").fancybox({
                    'titlePosition': 'inside',
                    'transitionIn': 'none',
                    'transitionOut': 'none'
                });
            },
            error:function(x,y,z){debugger;}
        });
    </script>
    namespace MVCSamples.Controllers
    {
        public class _2168647_how_to_show_popup_with_list_returned_by_ajax_result_set_and_how_to_select_item_and_return_it_back_to_parent_htmlController : Controller
        {
            public IActionResult Index()
            {
                
                return View();
            }
    
            public List<UserViewModel> GetUsers() {
                var users = new List<UserViewModel>();
                for (int i = 0; i < 20; i++)
                {
                    users.Add(GetRandomData.GetRandomDataObject<UserViewModel>());
                }
                return users;
            }
        }
    }

    Working sample here-

    https://github.com/anupdg/mvcsamples/tree/master/Views/_2168647_how_to_show_popup_with_list_returned_by_ajax_result_set_and_how_to_select_item_and_return_it_back_to_parent_html

    Friday, July 3, 2020 12:52 PM
  • User1094269964 posted

    Hi Thanks for the reply.

    using bootstrap I am able to show the modal popup but not able to get the selected items ..I dont know how to get the selected items from the modal popup

    here is the code. Can you help


    @{
    ViewBag.Title = "Index";
    }


    <h2>This is from Demo Index</h2>

    <div>
    <input type="text" id="txtFname" />
    <button class="btn btn-xs" id="btnSearch">
    <span>SearchByFirstName</span>
    </button>
    </div>


    <div id="MyPopup" class="modal fade" role="dialog">
    <div class="modal-dialog">
    <div class="modal-content">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">
    &times;
    </button>
    <h4 class="modal-title"></h4>
    </div>
    <div class="modal-body">
    </div>
    <div class="modal-footer">
    <button type="button" class="btn btn-danger" data-dismiss="modal">
    Close
    </button>
    </div>
    </div>
    </div>
    </div>

    @section scripts
    {
    <script>
    $("#btnSearch").click(function (e) {
    $.ajax({
    type: "POST",
    dataType: 'json',
    url: "/Demo/Search",
    data: {
    strUser: $("#txtFname").val()
    },
    success: function (result) {
    var $table = $('<table id="tmptable" class="table-condensed table-bordered">');
    var tr = "<tr><th>Action</th><th>UserId</th><th>UserName</th><th>Email</th><th>Phone</th></tr>"
    $table.append(tr)
    for (var i = 0; i < result.length; i++) {
    tr = "<tr><td><button type=\"button\" class=\"btn btnSelect\">Select</button></td>"+"<td>" + result[i].UserId + "</td><td>" + result[i].UserName + "</td><td>" + result[i].Email + "</td><td>" + result[i].Phone + "</td></tr>"
    $table.append(tr);
    }
    debugger;
    $("#MyPopup .modal-title").html("Select any one User");
    $("#MyPopup .modal-body").html($table[0].outerHTML);
    $("#MyPopup").modal("show");

    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
    debugger;

    }
    });
    });

    $(".btnSelect").click(function (e) {
    //here I want to do some activity based on items selected in the modal popup
    });

    </script>

    }

    Monday, July 13, 2020 6:13 PM
  • User-939850651 posted

    Hi bsurendiran,

    You could pass the data in each user record to the js method, and then do what you want to the operation.

    Just like this:

    $("#btnSearch").click(function (e) {
                $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "/Demo/SearchByFirstName",
                    data: {
                        strUser: $("#txtFname").val()
                    },
                    success: function (result) {
                        $("#modalTable").html("");
                        var tr = "<tr><th>Action</th><th>UserId</th><th>UserName</th><th>Email</th><th>Phone</th></tr>"
                        $("#modalTable").append(tr);
                        for (var user of result) {
                            tr = "<tr><td><button type=\"button\" onclick=\"myFunction('" + user.UserId + "')\" class=\"btn btnSelect\">Select</button></td><td>" + user.UserId + "</td><td>" +
                                user.UserName + "</td><td>" + user.Email +
                                "</td><td>" + user.Phone + "</td></tr>"
    
                            $("#modalTable").append(tr);
                        }
                        $('#myModal').modal('show');
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        debugger;
                        alert("Content load failed.");
                    }
                });
            });
    
            function myFunction(userId) {
                alert("UserId==>" + userId);
                //do something here
            }

    Result:

    Best regards,

    Xudong Peng 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 15, 2020 10:09 AM
  • User1094269964 posted

    thank you.

    Instead of passing just user id is it possible to pass entire object to that function something like this below?

     tr = "<tr><td><button type=\"button\" onclick=\"myFunction('" + user+ "')\" class=\"btn btnSelect\">Select</button></td><td>" + user.UserId + "</td><td>" +
                                user.UserName + "</td><td>" + user.Email +
                                "</td><td>" + user.Phone + "</td></tr>"
    Wednesday, July 15, 2020 3:21 PM
  • User348806598 posted

    Hi,

    You can do without passing complete object. In the button click, myFunction, event you can try this code-

    var containerRow = $(this).closest('tr');
    
    var userId =containerRow.find("td:nth-child(2)");
    var userName =containerRow.find("td:nth-child(3)");
    var userEmail =containerRow.find("td:nth-child(4)");
    var phone =containerRow.find("td:nth-child(5)");
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 16, 2020 3:44 AM