locked
How to open a modal window and pass the model to js RRS feed

  • Question

  • User1642770137 posted

    I learn modals and I have a problem.

    I have a controller that has 1 method that should update or add a record. But I don’t know how to do it on js.

    This is my main page

    <!-- Modal placeholder -->
    <div id="modal-placeholder"></div>
    
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="ajax-modal" id="modalButton">
        Add new pupil
    </button>
    
    <h1>Index</h1>
    <div id="Results"></div>
    
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Email)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Email)
                    </td>
                    <td>
                        <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                        <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                        <form asp-action="Delete" asp-route-id="@item.Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
                            <input type="submit" value="Delete" class="btn btn-danger" />
                        </form>
                    </td>
                </tr>
            }
        </tbody>
    </table>

    Then i click to the button and i want to open partialView in modal window.

    My model is simple

    public class Pupils
    {
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    }

    i try 

    getPupils = (url, title) => {
        $.ajax({
            type: 'GET',
            url: url,
            success: function (res) {
                $('#form-modal .modal-body').html(res);
                $('#form-modal .modal-title').html(title);
                $('#form-modal').modal('show');
            }
        })
    };
    
    const patentBox = $('#Results');
    const modalButton = $('#modalButton');
    
    modalButton.on('click', function () {
        debugger;
            $.ajax({
                url: 'Pupils/AddOrEdit/',
                type: "GET",
                success: function(content){
                    patentBox.html(content);
                    },
            error: function (data) {
            console.error(data.responseText);
            toastr.error('Error', '!!!');
        } });
    })
    
    
    editPupil = form => {
        try {
            $.ajax({
                type: 'POST',
                url: form.action,
                data: new FormData(form),
                contentType: false,
                processData: false,
                success: function (res) {
                    if (res.isValid) {
                        $('#view-all').html(res.html)
                        $('#form-modal .modal-body').html('');
                        $('#form-modal .modal-title').html('');
                        $.notify('submitted successfully', { globalPosition: 'top center', className: 'success' });
                        $('#form-modal').modal('hide');
                    }
                    else
                        $('#form-modal .modal-body').html(res.html);
                },
                error: function (err) {
                    console.log(err);
                }
            });
        } catch (ex) {
            console.log(ex);
        }
        return false;
    };
    
    $(function () {
        $("#loaderbody").addClass('hide');
    
        $(document).bind('ajaxStart', function () {
            $("#loaderbody").removeClass('hide');
        }).bind('ajaxStop', function () {
            $("#loaderbody").addClass('hide');
        });
    });

    partialView

    @model Models.Pupils
    
    @{
        ViewData["Title"] = "Index";
    }
    <div class="modal bd-example-modal-lg" tabindex="-1" role="dialog" id="form-modal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
    
    
                    <div class="row">
                        <div class="col-md-12">
                            <form asp-action="AddOrEdit" asp-route-id="@Model.Id" onsubmit="return editPupil(this);" autocomplete="off">
                                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                                <input type="hidden" asp-for="Id" />
                                <div class="col-md-8 order-md-1">
                                    <div class="row">
                                        <div class="mb-3">
                                            <label for="address">Pupil name</label>
                                            <label asp-for="Name" class="control-label"></label>
                                            <input type="text" asp-for="Name" class="form-control" id="Name" placeholder="">
                                            <span asp-validation-for="Name" class="text-danger"></span>
                                            <div class="invalid-feedback">
                                                Please enter valid name.
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label asp-for="Email" class="control-label"></label>
                                                <input asp-for="Email" class="form-control" />
                                                <span asp-validation-for="Email" class="text-danger"></span>
                                            </div>
                                        </div>
                                    <div class="form-group">
                                        <div class="col-md-6 offset-md-3">
                                            <input type="submit" value="Submit" class="btn btn-primary btn-block" />
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
    
    
                </div>
            </div>
        </div>
    </div>
    
    <div class="loaderbody" id="loaderbody">
        <div class="loader"></div>
    </div>
    

    Now Modal open but and have style display:none, dont want close and i dont know how pass to ajax my model

    Thursday, September 3, 2020 6:45 AM

Answers

  • User-1330468790 posted

    Hi holodgalina,

     

    I can see that there are at least two errors in your codes:

    1. You forget to add "$('#form-modal').modal('show');" in button "modalButton"'s click event 
    2. You don't send any request to get the page which is used to display all pupils.

    Besides, you include some redundant js functions which you might never use them.

    These functions are not helpful for us to target the problem. You should refactor the codes and make them clean.

     

    Let's back to the problem, you could refer to below codes:

     Index View:

    @model IEnumerable<Models.Pupils>;
    @{
        ViewData["Title"] = "Home Page";
    
    }
    
    <!-- Modal placeholder -->
    <div id="modal-placeholder"></div>
    
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="ajax-modal" id="modalButton">
        Add new pupil
    </button>
    
    <h1>Index</h1>
    <div id="Results"></div>
    
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Email)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Email)
                    </td>
                    <td>
                        <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                        <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                        <form asp-action="Delete" asp-route-id="@item.Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
                            <input type="submit" value="Delete" class="btn btn-danger" />
                        </form>
                    </td>
                </tr>
            }
        </tbody>
    </table>
    
    @section scripts{
        <script>
            getPupils = (url, title) => {
                $.ajax({
                    type: 'GET',
                    url: url,
                    success: function (res) {
                        $('#form-modal .modal-body').html(res);
                        $('#form-modal .modal-title').html(title);
                        $('#form-modal').modal('show');
                    }
                })
            };
    
            const patentBox = $('#Results');
            const modalButton = $('#modalButton');
    
            modalButton.on('click', function () {
                debugger;
                $.ajax({
                    url: '/Pupils/AddOrEdit',
                    type: "GET",
                    success: function (content) {
                        patentBox.html(content);
                        $('#form-modal').modal('show'); // Add this one row code to make the modal showing
                    },
                    error: function (data) {
                        console.error(data.responseText);
                        toastr.error('Error', '!!!');
                    }
                });
            })
    
    
            editPupil = form => {
                console.log(form.action);
                console.log(new FormData(form));
                try {
                    $.ajax({
                        type: 'POST',
                        url: form.action,
                        data: new FormData(form),
                        contentType: false,
                        processData: false,
                        success: function (res) {
                            
                            if (res.isValid) {
                                $('#form-modal .modal-body').html('');
                                $('#form-modal .modal-title').html('');
                               
                                $('#form-modal').modal('hide');
                                window.location.assign(res.url); // Redirect the page to re-get the content for pupil list
                            }
                            else
                                $('#form-modal .modal-body').html(res.html);
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    });
                } catch (ex) {
                    console.log(ex);
                }
                return false;
            };
    
            $(function () {
                $("#loaderbody").addClass('hide');
    
                $(document).bind('ajaxStart', function () {
                    $("#loaderbody").removeClass('hide');
                }).bind('ajaxStop', function () {
                    $("#loaderbody").addClass('hide');
                });
            });
        </script>
    
    }

    partial View:

    @model Models.Pupils
    
    @{
        ViewData["Title"] = "Index";
    }
    <div class="modal bd-example-modal-lg" tabindex="-1" role="dialog" id="form-modal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
    
    
                    <div class="row">
                        <div class="col-md-12">
                            <form asp-action="AddOrEdit" asp-route-id="@Model.Id" onsubmit="return editPupil(this);" autocomplete="off">
                                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                                <input type="hidden" asp-for="Id" />
                                <div class="col-md-8 order-md-1">
                                    <div class="row">
                                        <div class="mb-3">
                                            <label for="address">Pupil name</label>
                                            <label asp-for="Name" class="control-label"></label>
                                            <input type="text" asp-for="@Model.Name" class="form-control" id="Name" placeholder="">
                                            <span asp-validation-for="Name" class="text-danger"></span>
                                            <div class="invalid-feedback">
                                                Please enter valid name.
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label asp-for="Email" class="control-label"></label>
                                                <input asp-for="@Model.Email" class="form-control" />
                                                <span asp-validation-for="Email" class="text-danger"></span>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="col-md-6 offset-md-3">
                                                <input type="submit" value="Submit" class="btn btn-primary btn-block" />
                                            </div>
                                        </div>
                                    </div>
                            </form>
                        </div>
                    </div>
    
    
                </div>
            </div>
        </div>
    </div>
    
    <div class="loaderbody" id="loaderbody">
        <div class="loader"></div>
    </div>

    PupilsController:

     public static List<Pupils> pupilList = new List<Pupils>
                {
                    new Pupils
                    {
                        Id=1,
                        Name="Name1",
                        Email="Email1"
                    },
                    new Pupils
                    {
                        Id=2,
                        Name="Name2",
                        Email="Email2"
                    },
                    new Pupils
                    {
                        Id=3,
                        Name="Name3",
                        Email="Email3"
                    }
                };
    
            public IActionResult Index()
            {
                
                return View(pupilList);
            }
    
            [HttpGet]
            public IActionResult AddOrEdit()
            {
                int? maxId = pupilList.Max(p => (int?)p.Id);  // Get the next Id
    
                int nextId = (maxId == null) ? 1 : (int)maxId + 1;
    
                Pupils pupil = new Pupils()
                {
                    Id = nextId
                };
    
                return PartialView("_pupilsPartial", pupil);
            }
    
            [HttpPost]
            public IActionResult AddOrEdit(int Id, Pupils pupils)
            {
                pupilList.Add(pupils);
                return Json(new { isValid = true,url = Url.Action("Index")  });
            }

    Pupils model is the exactly same with yours.

     

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 7, 2020 10:19 AM

All replies

  • User475983607 posted

    Now Modal open but and have style display:none, dont want close and i dont know how pass to ajax my model

    The Bootstrap modal you are using has documentation that illustrates how vary modal content.  

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

    Typically, you are doing an edit so you can simply fetch the data from the current DOM rather than making unnecessary HTTP requests.  Anyway, this is the approach I use and it should simplify your design.

    Thursday, September 3, 2020 11:38 AM
  • User-1330468790 posted

    Hi holodgalina,

     

    I can see that there are at least two errors in your codes:

    1. You forget to add "$('#form-modal').modal('show');" in button "modalButton"'s click event 
    2. You don't send any request to get the page which is used to display all pupils.

    Besides, you include some redundant js functions which you might never use them.

    These functions are not helpful for us to target the problem. You should refactor the codes and make them clean.

     

    Let's back to the problem, you could refer to below codes:

     Index View:

    @model IEnumerable<Models.Pupils>;
    @{
        ViewData["Title"] = "Home Page";
    
    }
    
    <!-- Modal placeholder -->
    <div id="modal-placeholder"></div>
    
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="ajax-modal" id="modalButton">
        Add new pupil
    </button>
    
    <h1>Index</h1>
    <div id="Results"></div>
    
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Email)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Email)
                    </td>
                    <td>
                        <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                        <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                        <form asp-action="Delete" asp-route-id="@item.Id" onsubmit="return jQueryAjaxDelete(this)" class="d-inline">
                            <input type="submit" value="Delete" class="btn btn-danger" />
                        </form>
                    </td>
                </tr>
            }
        </tbody>
    </table>
    
    @section scripts{
        <script>
            getPupils = (url, title) => {
                $.ajax({
                    type: 'GET',
                    url: url,
                    success: function (res) {
                        $('#form-modal .modal-body').html(res);
                        $('#form-modal .modal-title').html(title);
                        $('#form-modal').modal('show');
                    }
                })
            };
    
            const patentBox = $('#Results');
            const modalButton = $('#modalButton');
    
            modalButton.on('click', function () {
                debugger;
                $.ajax({
                    url: '/Pupils/AddOrEdit',
                    type: "GET",
                    success: function (content) {
                        patentBox.html(content);
                        $('#form-modal').modal('show'); // Add this one row code to make the modal showing
                    },
                    error: function (data) {
                        console.error(data.responseText);
                        toastr.error('Error', '!!!');
                    }
                });
            })
    
    
            editPupil = form => {
                console.log(form.action);
                console.log(new FormData(form));
                try {
                    $.ajax({
                        type: 'POST',
                        url: form.action,
                        data: new FormData(form),
                        contentType: false,
                        processData: false,
                        success: function (res) {
                            
                            if (res.isValid) {
                                $('#form-modal .modal-body').html('');
                                $('#form-modal .modal-title').html('');
                               
                                $('#form-modal').modal('hide');
                                window.location.assign(res.url); // Redirect the page to re-get the content for pupil list
                            }
                            else
                                $('#form-modal .modal-body').html(res.html);
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    });
                } catch (ex) {
                    console.log(ex);
                }
                return false;
            };
    
            $(function () {
                $("#loaderbody").addClass('hide');
    
                $(document).bind('ajaxStart', function () {
                    $("#loaderbody").removeClass('hide');
                }).bind('ajaxStop', function () {
                    $("#loaderbody").addClass('hide');
                });
            });
        </script>
    
    }

    partial View:

    @model Models.Pupils
    
    @{
        ViewData["Title"] = "Index";
    }
    <div class="modal bd-example-modal-lg" tabindex="-1" role="dialog" id="form-modal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
    
    
                    <div class="row">
                        <div class="col-md-12">
                            <form asp-action="AddOrEdit" asp-route-id="@Model.Id" onsubmit="return editPupil(this);" autocomplete="off">
                                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                                <input type="hidden" asp-for="Id" />
                                <div class="col-md-8 order-md-1">
                                    <div class="row">
                                        <div class="mb-3">
                                            <label for="address">Pupil name</label>
                                            <label asp-for="Name" class="control-label"></label>
                                            <input type="text" asp-for="@Model.Name" class="form-control" id="Name" placeholder="">
                                            <span asp-validation-for="Name" class="text-danger"></span>
                                            <div class="invalid-feedback">
                                                Please enter valid name.
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label asp-for="Email" class="control-label"></label>
                                                <input asp-for="@Model.Email" class="form-control" />
                                                <span asp-validation-for="Email" class="text-danger"></span>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="col-md-6 offset-md-3">
                                                <input type="submit" value="Submit" class="btn btn-primary btn-block" />
                                            </div>
                                        </div>
                                    </div>
                            </form>
                        </div>
                    </div>
    
    
                </div>
            </div>
        </div>
    </div>
    
    <div class="loaderbody" id="loaderbody">
        <div class="loader"></div>
    </div>

    PupilsController:

     public static List<Pupils> pupilList = new List<Pupils>
                {
                    new Pupils
                    {
                        Id=1,
                        Name="Name1",
                        Email="Email1"
                    },
                    new Pupils
                    {
                        Id=2,
                        Name="Name2",
                        Email="Email2"
                    },
                    new Pupils
                    {
                        Id=3,
                        Name="Name3",
                        Email="Email3"
                    }
                };
    
            public IActionResult Index()
            {
                
                return View(pupilList);
            }
    
            [HttpGet]
            public IActionResult AddOrEdit()
            {
                int? maxId = pupilList.Max(p => (int?)p.Id);  // Get the next Id
    
                int nextId = (maxId == null) ? 1 : (int)maxId + 1;
    
                Pupils pupil = new Pupils()
                {
                    Id = nextId
                };
    
                return PartialView("_pupilsPartial", pupil);
            }
    
            [HttpPost]
            public IActionResult AddOrEdit(int Id, Pupils pupils)
            {
                pupilList.Add(pupils);
                return Json(new { isValid = true,url = Url.Action("Index")  });
            }

    Pupils model is the exactly same with yours.

     

    Demo:

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 7, 2020 10:19 AM