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

前端之家收集整理的这篇文章主要介绍了c# – MVC 4使用局部视图进行验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

编辑:

这是我的部分观点:

@model BuSIMaterial.Models.Person

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    BoxFor(model => model.FirstName,new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.FirstName)
        BoxFor(model => model.LastName,new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.LastName)
        BoxFor(model => model.NumNat,new { maxlength = 11 })
            @Html.ValidationMessageFor(model => model.NumNat)
        BoxFor(model => model.StartDate,new {@class = "datepicker",@placeholder="yyyy/mm/dd"})
            @Html.ValidationMessageFor(model => model.StartDate)
        BoxFor(model => model.EndDate,new { @class = "datepicker",@placeholder = "yyyy/mm/dd" })
            @Html.ValidationMessageFor(model => model.EndDate)
        

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

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

            $("#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,"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,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 });
    }
}                                                                                                    `

The ajax call to /Person/CreatePerson will look similar to

`

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

除了不显眼的验证,动态内容也无法轻松完成.检查链接unobtrusive validation on dynamically added partial view (not working)

原文链接:https://www.f2er.com/jquery/428185.html

猜你在找的jQuery相关文章