Search code examples
asp.netajaxasp.net-mvcasp.net-coreasp.net-core-mvc

Pre-filled forms in PopUp Modal ASP.NET Core MVC


I am trying to use a popup modal to edit a record on ASP.NET Core MVC. I have not been successful to prefill the modal form with the existing record on the edit functionality. Below is my simple model:

public class Student
{
    public int StudentId {get;set;}
    public string Name {get;set;}
}

I put a list of the object on the controller just for an example. Below is my controller:

public Home: Controller
{
    public static List<Student> studentList = new List<Student>()
    {
        new Student {StudentId = 1, Name = "John"},
        new Student {StudentId = 2, Name = "Doe"},
    };

    public IActionResult Index
    {
        return View(studentList);
    }

    public IActionResult Find(int id)
    {
        var student = studentList.Where(x => x.StudentId == id).FirstOrDefault();
        return new JsonResult(student);
    }

    [HttpPost]
    [Route("updateStudent")]
    public IActionResult updateStudent(int id, int name)
    {
        var student = studentList.Where(x => x.StudentId == id).FirstOrDefault();
        studentList.RemoveStudent();
        var newStudent = new Student{StudentId = id, Name=name};
        studentList.Add(newStudent);

        return RedirectToAction("Index");
    }
}

And in my view, I am using Jquery, ajax, and bootstrap for my modal. Below is part of my view:

<script type="text/javascript">
    $(document).ready(function(){
        $('[data-google="tooltip"]').tooltip();

        $('table .edit').on('click', function () {
            var id = $(this).parent().find('.id').val();
            $.ajax({
                type: 'GET',
                url: '/Home/Find/' + id,
                success: function(student) 
                {
                     $('#editStudentModal #id').val(student.StudentId);
                     $('#editStudentModal #id').val(student.Name);
                }
            })
        })
    });
</script>

<table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>StudentId</th>
                        <th>Name</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>
                                 @Html.DisplayFor(modelItem => item.StudentId)
                            </td>
                            <td>
                                 @Html.DisplayFor(modelItem => item.Name)
                            </td>
                            <td>
                                <a href="#editStudentModal" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a>
                                <input type="hidden" class="id" value="item.id" />
                            </td>
                        </tr>
                    }
                </tbody>
            </table>


<!--Edit Modal Html-->
    <div id="editStudentModal" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post" asp-controller="Home" asp-action="updateStudent">
                    <div class="modal-header">
                        <h4 class="modal-title">Edit Student</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                            <div class="form-group">
                                <label>Id</label>
                                <input type="text" class="form-control" required="required" name="id" />
                            </div>
                            <div class="form-group">
                                <label>Name</label>
                                <input type="text" class="form-control" required="required" name="name" />
                            </div>
                    </div>
                    <div class="modal-footer">
                        <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" />
                        <input type="Submit" class="btn btn-info" value="Save" />
                        <input type="hidden" id="id" name="id" />
                    </div>
                </form>
            </div>
        </div>
    </div>

But when I click the edit button, it the modal pops up but it is not prefilled with the chosen record. Can anyone help mt to fix this issue? I suspect something is wrong with my ajax.

Thanks


Solution

  • You could always press F12 to check the dev tools to find what the error is.In you case, there are several mistakes.

    1.<input type="hidden" class="id" value="item.id" />

    You need to use @item.id or @item.StudentId(based on the demo) to get the value while you are missing @ in the code.

    2.$('#editStudentModal #id').val(student.StudentId);

    Then you could use console.log(student) in ajax success to check the returned json:

    {studentId: 1, name: "John"}
    

    So, you need to use student.studentId instead of student.StudentId.

    3.Besides, since you use $('#editStudentModal #id'), it will find id="id" but you only set name="id", add id on the input or use below code to find the element:

    $('#editStudentModal input[name="id"]').val(student.studentId);
    $('#editStudentModal input[name="name"]').val(student.name);
    

    Complete Code

    @model List<Student>
    
    <table class="table table-striped table-hover">
        <thead>
            <tr>
                <th>StudentId</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.StudentId)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        <a href="#editStudentModal" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a>
                        <input type="hidden" class="id" value="@item.StudentId" />
                    </td>
                </tr>
            }
        </tbody>
    </table>
    
    
    <!--Edit Modal Html-->
    <div id="editStudentModal" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post" asp-controller="Home" asp-action="updateStudent">
                    <div class="modal-header">
                        <h4 class="modal-title">Edit Student</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Id</label>
                            <input type="text" class="form-control" required="required"  name="id" />
                        </div>
                        <div class="form-group">
                            <label>Name</label>
                            <input type="text" class="form-control" required="required"  name="name" />
                        </div>
                    </div>
                    <div class="modal-footer">
                        <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" />
                        <input type="Submit" class="btn btn-info" value="Save" />
                        <input type="hidden" id="id" name="id" />
                    </div>
                </form>
            </div>
        </div>
    </div>
    @section Scripts{
        <script type="text/javascript">
            $(document).ready(function () {
                $('[data-google="tooltip"]').tooltip();
    
                $('table .edit').on('click', function () {
                    var id = $(this).parent().find('.id').val();
                    $.ajax({
                        type: 'GET',
                        url: '/Home/Find/' + id,
                        success: function (student) {
                            console.log(student);
                            $('#editStudentModal input[name="id"]').val(student.studentId);
                            $('#editStudentModal input[name="name"]').val(student.name);
                        }
                    })
                })
            });
        </script>
    
    }
    

    Result:

    enter image description here