MVC 5验证错误消息未出现

时间:2015-04-08 12:55:40

标签: asp.net asp.net-mvc asp.net-mvc-4

我遇到一个问题,即验证消息没有出现在给定表单中。该表单显示在jQuery模式对话框中,当您单击主页面上的按钮时,该对话框将打开。

当我尝试提交所有字段为空的表单时,我应该得到错误,这些字段是必需的,但我不这样做。但是,如果我调试并进入Controller代码以查看哪些模型被报告为无效,我会看到此处提到的消息,这些字段是必需的。

我已尝试在提交完成后删除视图中使用的自定义JavaScript,但这并不能解决问题。

这是模型:

public class Expense : ActivityLog
    {
        [Key]
        public int ID { get; set; }
        public bool chargedBySeller { get; set; }
        public string chargingEntity { get; set; }
        [Required]
        public string chargeCurrency { get; set; }
        [Required]
        public double chargeAmount { get; set; }
        public DateTime chargeDate { get; set; }
        public bool countInExpensesTotalling { get; set; }
        [Required]
        public string paymentMethod { get; set; }
        public List<Refund> refundsDoneForThisCharge { get; set; }
    }

这是控制器:

public class PurchasesController : Controller
{
    private AppDbContext db = new AppDbContext();

    //Other Actions removed for brevity


    [HttpPost]
    public ActionResult AddOrEditExpense(Expense expense)
    {

        if (ModelState.IsValid)
        {
            if (Session["expensesList"] == null)
            {
                Session["expensesList"] = new List<Expense>();
            }

            if ((int)Session["expenseAddEditMode"] == 2) //ADD
            {
                ((List<Expense>)Session["expensesList"]).Add(expense);
            }
            else if ((int)Session["expenseAddEditMode"] == 1) //EDIT
            {
                ((List<Expense>)Session["expensesList"])[(int)Session["expenseEditIndex"]] = expense;
            }
        }

        return PartialView("~/Views/Purchases/Expense/ViewList.cshtml", Session["expensesList"]);
    }
}

最后,这是Razor View代码:

<script type="text/javascript">
    $(function () {
        $("#add-or-edit-expense-form").on("submit", function (e) {

            e.preventDefault();

            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    $("#expense-list-div").html(data);
                    $("#expense-dialog").dialog("close");
                }
            });
        });
    });
</script>


@model ExpOrderBluManagement_Web.Models.ApplicationModels.Expense

@using (Html.BeginForm("AddOrEditExpense", "Purchases", FormMethod.Post, new { id = "add-or-edit-expense-form" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Expense</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.chargedBySeller, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.chargedBySeller)
                    @Html.ValidationMessageFor(model => model.chargedBySeller, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.chargingEntity, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.chargingEntity, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.chargingEntity, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.chargeCurrency, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.chargeCurrency, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.chargeCurrency, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.chargeAmount, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.chargeAmount, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.chargeAmount, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.chargeDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.chargeDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.chargeDate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.countInExpensesTotalling, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.countInExpensesTotalling)
                    @Html.ValidationMessageFor(model => model.countInExpensesTotalling, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.paymentMethod, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.paymentMethod, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.paymentMethod, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

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

2 个答案:

答案 0 :(得分:2)

正如@Stephen一样,如果你动态地向DOM添加控件,你必须重新解析验证器。尝试编写这样的脚本:

<script type="text/javascript">
    $(function () {

        var $form = $("#add-or-edit-expense-form");
        $.validator.unobtrusive.parse($form);

        $form.on("submit", function (e) {    
            e.preventDefault();
            if($form.valid()) {
              $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    $("#expense-list-div").html(data);
                    $("#expense-dialog").dialog("close");
                }
              });
           }
        });
    });
</script>

添加 $。validator.unobtrusive.parse($ form); 此外,我会检查表单是否有效,然后执行ajax调用。

答案 1 :(得分:-1)

你在页面底部有jQuery Val,你有一个指向jQuery的链接