如何在bootstrap模式中显示服务器验证的错误?

时间:2017-10-10 00:46:28

标签: javascript c# jquery ajax asp.net-mvc

我在bootstrap模式中遇到服务器验证问题。我想用我的表单打开一个模态并做提交,但如果我的模型中存在一些错误,我想要显示错误消息。我不知道该怎么做。

我的控制器:

public ActionResult NovoComportamento(Guid id)
        {
            ViewBag.Icon = "icon-plus";
            ViewBag.Title = "Novo Comportamento de Componente";

            var comportamentoComponente = new ComportamentoComponenteViewModel();

            comportamentoComponente.ComponenteFormId = id;

            return PartialView("~/Views/ComportamentoComponente/_ComportamentoComponente.cshtml", comportamentoComponente);
        }

        [HttpPost]
        public ActionResult NovoComportamento(ComportamentoComponenteViewModel comportamentoComponenteViewModel)
        {
            var errorList = new List<ValidationError>();

            ViewBag.Icon = "icon-plus";
            ViewBag.Title = "Novo Comportamento de Componente";

            var componenteSalvoNoBanco = _componenteFormAppService.ObterPorId(comportamentoComponenteViewModel.ComponenteFormId);

            if (componenteSalvoNoBanco == null)
            {
                errorList.Add(new ValidationError("Não é permitido adicionar um comportamento a componente que não está salvo na base de dados."));
                return Json(new ActionResponse(false, errorList, comportamentoComponenteViewModel));
            }

            if (ModelState.IsValid)
            {
                var comportamentoReturn = _comportamentoComponenteAppService.Salvar(comportamentoComponenteViewModel, comportamentoComponenteViewModel.ComportamentoComponenteId);

                if (!comportamentoReturn.ValidationResult.IsValid)
                {
                    foreach (var error in comportamentoReturn.ValidationResult.Erros)
                    {
                        errorList.Add(new ValidationError(error.Message));
                    }

                    return Json(new ActionResponse(false, errorList, comportamentoComponenteViewModel), JsonRequestBehavior.AllowGet);
                }

                return Json(new ActionResponse(true, null, comportamentoComponenteViewModel), JsonRequestBehavior.AllowGet);
            }

            return Json(new ActionResponse(true, errorList, comportamentoComponenteViewModel), JsonRequestBehavior.AllowGet);
        }

我的部分视图采用模态形式:

@model PAD.Application.ViewModels.ComportamentoComponenteViewModel

<div class="modal-dialog">
    <div class="modal-content">
        @using (Ajax.BeginForm(null, null,
                        new AjaxOptions
                        {
                            HttpMethod = "POST",
                            InsertionMode = InsertionMode.Replace
                        },
                        new { id = "comportamentoComponenteFrm", onsubmit = "comportamentoSubmit()" }))
        {
            <div class="card-header modaldialog">
                <button class="close" type="button" data-dismiss="modal">
                    <span class="sr-only">Close</span>
                    <span aria-hidden="true">x</span>
                </button>
                <h4 class="card-title">
                    <span class="@ViewBag.Icon"></span> @ViewBag.Title
                </h4>
            </div>
            <div class="modal-body">
                <div class="card-block">
                    <div class="form-group">
                        <ul id="listaErros"></ul>
                    </div>
                    @Html.HiddenFor(model => model.ComponenteFormId)
                    <div class="form-body">
                        <div class="form-group">
                            @Html.LabelFor(model => model.Tipo)
                            <select class="form-control" name="tipo" id="combotipo">
                                <option value="">-- Selecionar --</option>
                                <option value="A">A - Acessibilidade</option>
                                <option value="P">P - Aparência</option>
                                <option value="V">V - Visibilidade</option>
                            </select>
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.Condicao)
                            @Html.TextAreaFor(model => model.Condicao, new { @class = "form-control", @rows = "10" })
                        </div>
                        <div class="form-group" id="classe-group">
                            @Html.LabelFor(model => model.Classe)
                            @Html.TextBoxFor(model => model.Classe, htmlAttributes: new { @class = "form-control" })
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-footer">
                <button class="btn btn-warning shadow" type="button" id="voltar-lista-comportamentos">
                    <span class="icon-reply"></span> Voltar
                </button>
                <button class="btn btn-success shadow pull-right" type="submit">
                    <span class="icon-check"></span> Salvar
                </button>
            </div>
        }
    </div>
</div>

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

<script src="~/Content/js/comportamento-componente.js"></script>

我的javascript:

$(document).ready(function () {

    $("#classe-group").hide();

    $("#combotipo").change(function () {
        var tipo = $("#combotipo").val();

        if (tipo == "P") {
            $("#classe-group").show('slow');
        } else {
            $("#classe-group").hide('slow');
        }
    });

    var componenteFormId = $("#componente-id").val();

    $("#btnNovoComportamento").click(function () {
        var url = "/ComportamentoComponente/NovoComportamento/";
        $("#modal").load(url + componenteFormId, function () {
            $("#modal").modal("show");
        });
    });

    $("#voltar-lista-comportamentos").click(function () {
        var url = "/ComportamentoComponente/ListaComportamentosComponente/";

        if (componenteFormId == "" || componenteFormId == undefined || componenteFormId == null) {
            swal("Erro", "Nenhum componente foi selecionado!", "error");
        } else {
            $("#modal").load(url + componenteFormId, function () {
                $("#modal").modal("show");
            });
        }
    });

    function comportamentoSubmit(event) {
        event.preventDefault();

        $.ajax({
            type: 'POST',
            url: '/comportamentocomponente/novocomportamento',
            data: $("#comportamentoFrm").serialize(),
        }).done(function (result) {
            swal("OK!", "A requisição foi feita.", "success");
            if (result.data != null && !result.data.success) {
                swal("OPS!", "Existem alguns erros.", "error");
                var errors = result.data.errorList;
                $.each(errors, function (key, value) {
                    $("#listaErros").append("<li>" + value + "</li>");
                });
            } else {
                swal("OK!", "Comportamento de Componente cadastrado com sucesso!", "success");
                $("#modal").modal("hide");
                $("#comportamentoFrm").html(result);
            }
        });
    }
});

我知道应该使用Json,但不知道如何使用javascript获得结果并在部分视图模式中显示错误而不关闭模态。我想在不存在错误时关闭模态。

这是退货提交:

enter image description here

1 个答案:

答案 0 :(得分:0)

我喜欢那种

控制器中的

 [HttpPost]
    public JsonResult yourMethode(model myModel)
    {
     var errorModel = from x in ModelState.Keys where ModelState[x].Errors.Count > 0 select new { key = x, errors = ModelState[x].Errors[0].ErrorMessage };
                return Json(new { Error = true, Data = errorModel, responseText = "Erreur Model" });
    }

在jquery ajax错误

 error: function (request, error) {
 if (JSON.parse(request.responseText).Data[0] != null) {console.log(JSON.parse(request.responseText).Data[0].errors)}
}