J'apprends les modaux et j'ai un problème. Maintenant, le modal est ouvert mais a un affichage de style : aucun, il ne veut pas fermer la fenêtre et je ne sais pas comment passer à ajax mon modèle

J'ai un contrôleur qui a 1 méthode qui devrait mettre à jour ou ajouter un enregistrement. Mais je ne sais pas comment faire sur js.

Ceci est ma page principale

    <!-- 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>

Ensuite, je clique sur le bouton et je veux ouvrir partialView dans la fenêtre modale. Mon modèle est simple

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

J'essaie

    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');
    });
});

Vue partielle

    @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>
0
cickness 5 sept. 2020 à 18:53

1 réponse

Meilleure réponse

Voici une démo complète de travail comme ci-dessous:

Index.cshtml:

@model IEnumerable<Pupils>
<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 onclick="Edit(@item.Id)" style="color: #007bff">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>

Js dans Index.cshtml :

@section Scripts{
<script>  
    const patentBox = $('#Results');
    const modalButton = $('#modalButton');
    modalButton.on('click', function () {
        debugger;
        $.ajax({
            url: '/Home/Add',
            type: "GET",
            success: function (content) {
                patentBox.html(content);
                $('#form-modal').modal('show');
            },
            error: function (data) {
                console.error(data.responseText);
                toastr.error('Error', '!!!');
            }
        });
    });
    function Edit(id) {
        $.ajax({
            url: '/Home/Edit?id='+id,
            type: "GET",
            success: function (content) {
                patentBox.html(content);
                $('#form-modal').modal('show');
            },
            error: function (data) {
                console.error(data.responseText);
                toastr.error('Error', '!!!');
            }
        });
    };
    addPupil = form => {
        try {
            $.ajax({
                type: 'POST',
                url: form.action,
                data: new FormData(form),
                contentType: false,
                processData: false,
                success: function (res) {
                    console.log(res.isValid);
                    if (res.isValid) {
                        window.location.href = res.url;
                        $('#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;
    };
    editPupil = form => {
        try {
            $.ajax({
                type: 'POST',
                url: form.action,
                data: new FormData(form),
                contentType: false,
                processData: false,
                success: function (res) {
                    if (res.isValid) {
                        window.location.href = res.url;
                        $('#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;
    };
</script>
}

_PartialAdd.cshtml :

@model Pupils
<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="Add" onsubmit="return addPupil(this);" autocomplete="off">
                            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                            <input type="hidden" asp-for="Id" />
                            <div class="row">
                                <div class="col-md-8 order-md-1">
                                    <div class="form-group">
                                        <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="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 class="form-group">
                                        <input type="submit" value="Submit" class="btn btn-primary btn-block" />
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>      
            </div>
        </div>
    </div>
</div>

_PartialEdit.cshtml :

@model Pupils
<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="Edit" 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="row">
                                <div class="col-md-8 order-md-1">
                                    <div class="form-group">
                                        <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="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 class="form-group">
                                        <input type="submit" value="Submit" class="btn btn-primary btn-block" />
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>      
            </div>
        </div>
    </div>
</div>

Manette:

public class HomeController : Controller
{
    private readonly Mvc3_1Context _context;
    public HomeController(Mvc3_1Context context)
    {
        _context = context;
    }
    public IActionResult Index()
    {
        var model = _context.Pupils.ToList();
        return View(model);
    }
    public IActionResult Add()
    {
        return PartialView("_PartialAdd");
    }
    [HttpPost]
    public async Task<IActionResult> Add([Bind("Name,Email")] Pupils pupils)
    {
        if (!ModelState.IsValid)
        {
            return Json(new { isValid = false });
        }
        _context.Add(pupils);
        await _context.SaveChangesAsync();
        return Json(new { isValid = true, url = "/Home/Index" });
    }
    public IActionResult Edit(int id)
    {
        var pupil = _context.Pupils.Find(id);
        return PartialView("_PartialEdit", pupil);
    }
    [HttpPost]
    public async Task<IActionResult> Edit(int id, Pupils pupils)
    {
        if (id != pupils.Id)
        {
            return NotFound();
        }
        if (!ModelState.IsValid)
        {
            return Json(new { isValid = false });
        }
        _context.Update(pupils);
        await _context.SaveChangesAsync();
        return Json(new { isValid = true, url = "/Home/Index" });
    }
}

Résultat: entrez la description de l'image ici

0
Rena 7 sept. 2020 à 03:45