MVC Bootstrap模式显示验证结果

时间:2017-11-08 08:06:07

标签: asp.net-mvc jquery-validate bootstrap-modal unobtrusive-validation

问题:

我希望提交提交到模态的表单,如果验证faild,则在模态上获取错误消息。

我使用ajax验证(jQuery)作为详细的here

是否有一种优雅的方式来执行提交但是在faild停留在模态以显示错误消息?

我的代码:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Cam c)
    {
        ViewBag.id = c.id;

        using (Entities db = new Entities())
        {
            if (ModelState.IsValid)
            {
                db.camp.Add(c);
                db.SaveChanges();
                return RedirectToAction("Index", new { id = c.id });
            }

        }
        return null;
    }

客户端:

@using (Html.BeginForm("Create", "Camp", FormMethod.Post, new { model = 
Model }))
{
@Html.AntiForgeryToken()

<dt>
            name:
        </dt>
        <dd>
            @Html.TextBoxFor(model => model.name, new { @class = "form-control", @placeholder = "name", @id = "txtVenueID", style = "width:150px" })
        </dd>

        <dd>
            @Html.ValidationMessageFor(model => model.name)
        </dd>
<div class="modal-footer ">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}

型号:

public partial class Cam
{

    [Display(Name = "Name")]
    [Required(ErrorMessage = "Require {0}")]
    string name { get; set; }
}

1 个答案:

答案 0 :(得分:0)

  1. 通过构建它的操作显示模态中的第一个表单,但保持模型状态错误 - 使用This
  2. 要查看提交表单但保留结果模式,请使用以下内容:

    <button type="submit" class="btn btn-primary">Save</button>
    
  3. Javascript将提交结果输入模态:

    $(function () {
        $.ajaxSetup({ cache: false });
    
        $(':submit[data-modal]').on("click", function (e) {
        e.preventDefault();
        var linkObj = $(this).closest('form');
            $.ajax({ // create an AJAX call...
                data: linkObj.serialize(), // get the form data
                type: linkObj.attr('method'), // GET or POST
                url: linkObj.attr('action'), // the file to call
                success: function(response) { // on success..
                    $('#Modal-Content').html(response); // update the DIV
                }
            });
        });
    });