Submitting data from a Bootstrap modal popup

耗尽温柔 提交于 2021-02-11 14:00:57

问题


I'd like my users to be able to submit data from a Bootstrap modal popup.

I'm wondering if anyone has experience doing this, and how you posted the data back to the server. Razor Pages have a lot of structure in place to deal with errors, etc. and it seems like you'd lose all that.

Did you place the <form> tag right inside the modal popup? In this case, it appears there is no way to handle server-side errors. (Or did you find a way?)

Or did you submit the data using AJAX, which requires some more work but you could report errors however you wanted.


回答1:


Here a complete demo how to re-open a modal after a form post when there are errors. This demo is made with MVC and Bootstrap 4. For the front-end validation to work this assumes you have the default MVC jquery.validate added to the skin.

So first a Model

public class ModalFormDemoModel
{
    [Display(Name = "Email address")]
    [Required(ErrorMessage = "Your email address is required.")]
    [EmailAddress(ErrorMessage = "Incorrect email address.")]
    public string EmailAddress { get; set; }

    [Display(Name = "First name")]
    public string FirstName { get; set; }

    [Display(Name = "Last name")]
    [Required(ErrorMessage = "Your last name is required.")]
    [StringLength(50, MinimumLength = 3, ErrorMessage = "Your last name is too short.")]
    public string LastName { get; set; }

    public string ResultMessage { get; set; }
}

Then the html and razor

@model WebApplication1.Models.ModalFormDemoModel

@{
    ViewBag.Title = "Modal Form Demo";
}

<div class="container">

    @if (!string.IsNullOrEmpty(Model.ResultMessage))
    {
        <div class="row">
            <div class="col">

                <div class="alert alert-success" role="alert">
                    @Model.ResultMessage
                </div>

            </div>
        </div>
    }

    <div class="row">
        <div class="col">

            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                Open Modal
            </button>

        </div>
    </div>

</div>


<div class="modal fade" id="exampleModal" 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">Modal Form Demo</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

                @using (Html.BeginForm("Index", "Home", FormMethod.Post))
                {
                    <div class="container-fluid">

                        <div class="row">
                            <div class="col">

                                @Html.ValidationSummary()

                            </div>
                        </div>

                        <div class="row">
                            <div class="col">
                                <div class="form-group">

                                    @Html.LabelFor(m => m.FirstName)
                                    @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control", maxlength = 25 })
                                    @Html.ValidationMessageFor(m => m.FirstName)

                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col">
                                <div class="form-group">

                                    @Html.LabelFor(m => m.LastName)
                                    @Html.TextBoxFor(m => m.LastName, new { @class = "form-control", maxlength = 50 })
                                    @Html.ValidationMessageFor(m => m.LastName)

                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col">
                                <div class="form-group">

                                    @Html.LabelFor(m => m.EmailAddress)
                                    @Html.TextBoxFor(m => m.EmailAddress, new { @class = "form-control", maxlength = 100 })
                                    @Html.ValidationMessageFor(m => m.EmailAddress)

                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col">

                                <button class="btn btn-primary" type="submit">
                                    Submit Form
                                </button>

                            </div>
                            <div class="col">

                                <button class="btn btn-secondary float-right" type="button" data-dismiss="modal">
                                    Cancel
                                </button>

                            </div>
                        </div>

                    </div>

                    @Html.AntiForgeryToken()
                }

            </div>
        </div>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

The controller code

public ActionResult Index()
{
    return View(new ModalFormDemoModel());
}


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(ModalFormDemoModel model)
{
    //add a custom error
    ModelState.AddModelError(string.Empty, "This is a custom error for testing!");

    //check the model (you should also do front-end vlidation, as in the demo)
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    //do your stuff


    //add a success user message
    model.ResultMessage = "Your form has been submitted.";

    return View(model);
}

And finally some javascript to open the modal if the ValidationSummary is active. The ValidationSummary generates html with the class validation-summary-errors, so we can look for that.

$(document).ready(function () {
    if ($('.validation-summary-errors').length) {
        $('#exampleModal').modal('show');
    }
});


来源:https://stackoverflow.com/questions/61601923/submitting-data-from-a-bootstrap-modal-popup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!