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

2023-11-26

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

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

EDIT :

这是我的部分观点:

@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 });
            }
        }

如果您发布页面,它将不会返回到动态加载的部分视图。尝试对 /Person/CreatePerson 进行 ajax 调用。您的 CreatePerson 将类似于

[HttpPost]
    public JsonResult CreatePerson(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 });
    }
}                                                                                                    `

对 /Person/CreatePerson 的 ajax 调用看起来类似于

`

$.ajax({
                url: '/Person/CreatePerson',
                type: "POST",
                data: $("#form").serialize(),
                success: function (responce) {
                    alert(responce.Message);
                },
                error: function (xhr, textStatus) {
                    alert(xhr.status + " " + xhr.statusText);
                }
            });

此外,不引人注目的验证无法轻松地处理动态内容。检查链接对动态添加的部分视图进行不显眼的验证(不起作用)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVC 4 使用部分视图进行验证 的相关文章

随机推荐