How to use bootstrap modal to edit the table data in MVC?

前端 未结 2 444
再見小時候
再見小時候 2020-12-23 15:44

I have a table in MVC view that displays employee details. I\'d like to add an edit functionality, but instead of opening it in a new page, I\'d like to show it using a boot

2条回答
  •  [愿得一人]
    2020-12-23 15:55

    There are indeed 2 possibilities: with or without AJAX. If you want to do that without AJAX you could subscribe to the click event of the Edit link and then copy the values from the table to the modal and finally show the modal.

    So start by giving your edit link some class:

    Edit
    

    that you could subscribe to:

    $('a.edit').on('click', function() {
        var myModal = $('#myModal');
    
        // now get the values from the table
        var firstName = $(this).closest('tr').find('td.firstName').html();
        var lastName = $(this).closest('tr').find('td.lastName').html();
        ....
    
        // and set them in the modal:
        $('.firstName', myModal).val(firstName);
        $('.lastNameName', myModal).val(lastName);
        ....
    
        // and finally show the modal
        myModal.modal({ show: true });
    
        return false;
    });
    

    This assumes that you have given proper CSS classes to the elements and the input fields in your modal.


    If you wanted to use AJAX you could generate the link like that:

    @Html.ActionLink("Edit", "Edit", "Employees", new { id = employee.Id }, new { @class = "btn edit" })
    

    and then you subscribe to the click event of this button and trigger the AJAX request:

    $('a.edit').on('click', function() {
        $.ajax({
            url: this.href,
            type: 'GET',
            cache: false,
            success: function(result) {
                $('#myModal').html(result).find('.modal').modal({
                    show: true
                });
            }
        });
    
        return false;
    });
    

    you will have a simple placeholder for the modal in your main view that will harbor the details:

    The controller action that will be hit should fetch the employee record using the id an dpass it to a partial view:

    public ActionResult Edit(int id)
    {
        Employee employee = repository.Get(id);
        EmployeeViewModel model = Mapper.Map(employee);
        return PartialView(model);
    }
    

    and finally the corresponding partial:

    @model EmployeeViewModel
    
    
    

    Obviously you will also need to wrap the input fields into an Html.BeginForm that will allow you to send the updated details of the employee to the server. It might also be necessary to AJAXify this form if you want to stay on the same page.

提交回复
热议问题