locked
Bootstrap modal popup, HiddenFieldFor, MVC, EF RRS feed

  • Question

  • User1887783426 posted

    Hi. I have a page with all the records being listed. I have the records which can be uniquely identified because I have used @Html.HiddenFor for every record.

    The 'id' for each row is unique: 1,2,3...

    Now, if I want to take data to server side from Bootstrap modal popup then how can I use jQuery to get hold of a particular record that has unique ids and use $.ajax()?

    Tuesday, March 26, 2019 11:44 AM

Answers

  • User-2054057000 posted

    Hello Friend, 

    I created the working code for your scenario where the data is taken from View to Controller using jQuery AJAX method. Next, in the controller the relevant record is fetched (from a repository which can be a database), then this record's data is returned to the View in JSON format

    In the View I am showing the data inside a Bootstrap Model.

    This is how the code will work:

    Creating a Repository

    In my case it is Student.cs class which is added to the Models folder.

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int Standard { get; set; }
        public string City { get; set; }
    }
    

    Creating a Controller

    I created a controller called StudentController.cs inside the Controllers folder of my project.

    public class StudentController : Controller
    {
        // GET: Student
        public ActionResult Index()
        {
            return View();
        }
    
        [HttpPost]
        public JsonResult GetStudentData(int id)
        {
            List<Student> studentList = CreateStudents();
            Student student = studentList.Where(a => a.Id == id).FirstOrDefault();
            return Json(student);
        }
    
        public List<Student> CreateStudents()
        {
            List<Student> studentList = new List<Student>()
            {
                new Student(){ Id=1, Name="Ram", Age=11, Standard=9, City="New York" },
                new Student(){ Id=2, Name="Jack", Age=8, Standard=5, City="New Jersey" },
                new Student(){ Id=3, Name="Alex", Age=7, Standard=4, City="Boston" },
                new Student(){ Id=4, Name="Pamela", Age=12, Standard=10, City="Albany" }
            };
            return studentList;
        }
    }
    

    I will be calling this GetStudentData() action method from the .ajax() jQuery method on the View. It will get the student's id in it's parameter, then it searches the id in the student's repository. Finally it will return the corresponding student's record in JSON format to the View.

    Creating a View

    Now add the View with the following code:

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Index</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    
    </head>
    <body>
        <div class="container">
            <h2>Click the Students Records to see there Details</h2>
    
            <div id="studDiv">
                <p><a href="#" data-id="1">Student 1</a></p>
                <p><a href="#" data-id="2">Student 2</a></p>
                <p><a href="#" data-id="3">Student 3</a></p>
                <p><a href="#" data-id="4">Student 4</a></p>
            </div>
    
            <!-- Bootstrap Modal -->
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">Student Details</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <table class="table table-sm table-bordered">
                                <tr>
                                    <td>Id</td>
                                    <td id="stuId"></td>
                                </tr>
                                <tr>
                                    <td>Name</td>
                                    <td id="stuName"></td>
                                </tr>
                                <tr>
                                    <td>Age</td>
                                    <td id="stuAge"></td>
                                </tr>
                                <tr>
                                    <td>Standard</td>
                                    <td id="stuStandard"></td>
                                </tr>
                                <tr>
                                    <td>City</td>
                                    <td id="stuCity"></td>
                                </tr>
                            </table>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
    
        </div>
    <!-- END Bootstrap Modal --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script> $(document).ready(function () { $("#studDiv a").click(function (e) { $.ajax({ url: '@Url.Action("GetStudentData")', type: 'post', dataType: 'json', data: '{"id":"' + $(this).attr("data-id") + '"}', contentType: 'application/json; charset=utf-8', success: function (data) { $("#stuId").text(data["Id"]); $("#stuName").text(data["Name"]); $("#stuAge").text(data["Age"]); $("#stuStandard").text(data["Standard"]); $("#stuCity").text(data["City"]); $("#myModal").modal("show"); }, error: function (xhr, status, error) { console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) } }); }); }); </script> </body> </html>

    You can see that inside the .ajax() method the Controller's Action called GetStudentData() is invoked. I am passing the data-id value of the clicked anchor tag with my AJAX call like this - data: '{"id":"' + $(this).attr("data-id") + '"}'

    Once the AJAX response is got the the student's information is shown inside the bootstrap model.

    Rest of the code is easy to understand. 

    Reference - jQuery AJAX Complete Guide for Beginners and Experts – 7 Examples with Codes

    Hope it helps you.

    Regards...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 1, 2019 10:16 AM

All replies

  • User1520731567 posted

    Hi Wonderous,

    According to requirement,I think this demo meet your need:

    https://forums.asp.net/post/6209612.aspx

    I suggest you could use Partial View to get more data from database to view.

    Then you could use model popup to show the Partial View when user click the details button.

     $(function () {
                $(".anchorDetail").click(function () {
                    var $buttonClicked = $(this);
                    var id = $buttonClicked.attr('data-id');
                    $.ajax({
                        type: "GET",
                        url: '/Authors/myModal',//add a Partial View in controller
                        contentType: "application/json; charset=utf-8",
                        data: { "Id": id },
                        datatype: "json",
                        success: function (data) {
                            $('#myModalContent').html(data);
                            $('#myModal').modal('show');
    
                        },
                        error: function () {
                            alert("Dynamic content load failed.");
                        }
                    });
                });
            });

    If you have any questions,feel free to let me know and post more code so that I can reproduce your issue.

    Best Regards.

    Yuki Tao

    Wednesday, March 27, 2019 6:33 AM
  • User1887783426 posted

    Hi. In the following statement:

    var id = $buttonClicked.attr('data-id');

    I want to know if 'data-id' has already been there since start of asp.net.

    Was there any other alternative that gives me 'id' on clicking button present in the row of a record?

    What purpose does 'HiddenFor' serve in the context of performing CRUD?

    Thanks!

    Wednesday, March 27, 2019 8:30 AM
  • User1520731567 posted

    Hi Wonderous,

    var id = $buttonClicked.attr('data-id');

    I want to know if 'data-id' has already been there since start of asp.net.

    No,This is just a custom attribute.You don't need to have to follow it completely.

    Was there any other alternative that gives me 'id' on clicking button present in the row of a record?

    Of course.

    For example:

    You could use onclick() event to pass id.

    @foreach (var item in Model)
        {
    
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.FirstName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.LastName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Salary)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Department)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Position)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ViewDetails)
                </td>
                <td>
               
                    <a href="javascript:void(0);" onclick="doDetail(@item.Id);" >Details</a>
    </td> </tr> } </table> @section scripts { <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/bootstrap.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <script> var TeamDetailPostBackURL = '/Authors/myModal'; $(function () {
    function doDetail(id) { $.ajax({ type: "GET", url: TeamDetailPostBackURL, contentType: "application/json; charset=utf-8", data: { "Id": id }, datatype: "json", success: function (data) { $('#myModalContent').html(data); $('#myModal').modal('show'); }, error: function () { alert("Dynamic content load failed."); } }); }
    }); </script> }

    What purpose does 'HiddenFor' serve in the context of performing CRUD?

    It creates a hidden input on the form for the field (from your model) that you pass it.

    It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.

    As my opinion,It is an invisible container for storing data.

    Use it is often related to your needs.

    Best Regards.

    Yuki Tao

    Thursday, March 28, 2019 2:51 AM
  • User-2054057000 posted

    Hello Friend, 

    I created the working code for your scenario where the data is taken from View to Controller using jQuery AJAX method. Next, in the controller the relevant record is fetched (from a repository which can be a database), then this record's data is returned to the View in JSON format

    In the View I am showing the data inside a Bootstrap Model.

    This is how the code will work:

    Creating a Repository

    In my case it is Student.cs class which is added to the Models folder.

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int Standard { get; set; }
        public string City { get; set; }
    }
    

    Creating a Controller

    I created a controller called StudentController.cs inside the Controllers folder of my project.

    public class StudentController : Controller
    {
        // GET: Student
        public ActionResult Index()
        {
            return View();
        }
    
        [HttpPost]
        public JsonResult GetStudentData(int id)
        {
            List<Student> studentList = CreateStudents();
            Student student = studentList.Where(a => a.Id == id).FirstOrDefault();
            return Json(student);
        }
    
        public List<Student> CreateStudents()
        {
            List<Student> studentList = new List<Student>()
            {
                new Student(){ Id=1, Name="Ram", Age=11, Standard=9, City="New York" },
                new Student(){ Id=2, Name="Jack", Age=8, Standard=5, City="New Jersey" },
                new Student(){ Id=3, Name="Alex", Age=7, Standard=4, City="Boston" },
                new Student(){ Id=4, Name="Pamela", Age=12, Standard=10, City="Albany" }
            };
            return studentList;
        }
    }
    

    I will be calling this GetStudentData() action method from the .ajax() jQuery method on the View. It will get the student's id in it's parameter, then it searches the id in the student's repository. Finally it will return the corresponding student's record in JSON format to the View.

    Creating a View

    Now add the View with the following code:

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Index</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    
    </head>
    <body>
        <div class="container">
            <h2>Click the Students Records to see there Details</h2>
    
            <div id="studDiv">
                <p><a href="#" data-id="1">Student 1</a></p>
                <p><a href="#" data-id="2">Student 2</a></p>
                <p><a href="#" data-id="3">Student 3</a></p>
                <p><a href="#" data-id="4">Student 4</a></p>
            </div>
    
            <!-- Bootstrap Modal -->
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">Student Details</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <table class="table table-sm table-bordered">
                                <tr>
                                    <td>Id</td>
                                    <td id="stuId"></td>
                                </tr>
                                <tr>
                                    <td>Name</td>
                                    <td id="stuName"></td>
                                </tr>
                                <tr>
                                    <td>Age</td>
                                    <td id="stuAge"></td>
                                </tr>
                                <tr>
                                    <td>Standard</td>
                                    <td id="stuStandard"></td>
                                </tr>
                                <tr>
                                    <td>City</td>
                                    <td id="stuCity"></td>
                                </tr>
                            </table>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
    
        </div>
    <!-- END Bootstrap Modal --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script> $(document).ready(function () { $("#studDiv a").click(function (e) { $.ajax({ url: '@Url.Action("GetStudentData")', type: 'post', dataType: 'json', data: '{"id":"' + $(this).attr("data-id") + '"}', contentType: 'application/json; charset=utf-8', success: function (data) { $("#stuId").text(data["Id"]); $("#stuName").text(data["Name"]); $("#stuAge").text(data["Age"]); $("#stuStandard").text(data["Standard"]); $("#stuCity").text(data["City"]); $("#myModal").modal("show"); }, error: function (xhr, status, error) { console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) } }); }); }); </script> </body> </html>

    You can see that inside the .ajax() method the Controller's Action called GetStudentData() is invoked. I am passing the data-id value of the clicked anchor tag with my AJAX call like this - data: '{"id":"' + $(this).attr("data-id") + '"}'

    Once the AJAX response is got the the student's information is shown inside the bootstrap model.

    Rest of the code is easy to understand. 

    Reference - jQuery AJAX Complete Guide for Beginners and Experts – 7 Examples with Codes

    Hope it helps you.

    Regards...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 1, 2019 10:16 AM