MVC 4使用局部视图进行验证

问题描述 投票:5回答:3

我正在使用MVC 4和Entity Framework来开发一个Web应用程序。我正在使用加载了javascript的部分视图。其中之一是包含验证的创建视图。这就是我的问题:验证。我有一个自定义验证逻辑,例如,如果用户在某个字段(如“名称”)中输入某些数字,则会显示错误。

在这里,使用部分视图,它将我的部分视图重定向到显示的错误,但我想要做的是保持在我的主视图(索引视图)并保留显示错误的部分视图。

编辑:

这是我的部分观点:

@model BuSIMaterial.Models.Person

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Person</legend>

        <div class="editor-label">
            First name : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            Last name : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            National number : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.NumNat, new { maxlength = 11 })
            @Html.ValidationMessageFor(model => model.NumNat)
        </div>

        <div class="editor-label">
            Start date : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.StartDate, new {@class = "datepicker", @placeholder="yyyy/mm/dd"})
            @Html.ValidationMessageFor(model => model.StartDate)
        </div>

        <div class="editor-label">
            End date : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.EndDate, new { @class = "datepicker", @placeholder = "yyyy/mm/dd" })
            @Html.ValidationMessageFor(model => model.EndDate)
        </div>

        <div class="editor-label">
            Distance House - Work (km) : 
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.HouseToWorkKilometers)
            @Html.ValidationMessageFor(model => model.HouseToWorkKilometers)
        </div>

        <div class="editor-label">
            Category : 
        </div>
        <div class="editor-field">
            @Html.DropDownList("Id_ProductPackageCategory", "Choose one ...")
            @Html.ValidationMessageFor(model => model.Id_ProductPackageCategory) <a href = "../ProductPackageCategory/Create">Add a new category?</a>
        </div>

        <div class="editor-label">
            Upgrade? : 
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Upgrade)
            @Html.ValidationMessageFor(model => model.Upgrade)
        </div>

        <br />

        <div class="form-actions">
          <button type="submit" class="btn btn-primary">Create</button>
        </div>
    </fieldset>
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/themes/base/css")
}

在我看来,索引,我有这个:

<div class="form-actions"><button type="button" id="create" class="btn btn-primary">Create</button> </div>
<div id ="create_person"></div>

以及我加载部分视图的方式:

            $("#create").click(function () {
                var form = $("#create_person").closest("form");
                form.removeData('validator');
                form.removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse(form);

                $.ajax({
                    url: "/Person/CreateOrUpdate",
                    type: "POST",
                    data: $("#create_person").serialize(),
                    cache: false
                });

//                var url = '/Person/CreatePerson';
//                $("#create_person").load(url);

            });

行动 :

[HttpGet]
        public ActionResult CreateOrUpdate()
        {
            ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name");
            return View();
        }


        [HttpPost]
        public JsonResult CreateOrUpdate(Person person)
        {
            ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);

            try
            {
                if (!ModelState.IsValid)
                {
                    string messages = string.Join("; ", ModelState.Values
                                        .SelectMany(x => x.Errors)
                                        .Select(x => x.ErrorMessage));
                    throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
                }

                db.Persons.AddObject(person);
                db.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }
c# jquery ajax asp.net-mvc partial-views
3个回答
© www.soinside.com 2019 - 2024. All rights reserved.