【问题标题】:Jquery post and unobtrusive ajax validation not working mvc 4Jquery post和不显眼的ajax验证不起作用mvc 4
【发布时间】:2015-05-13 07:25:43
【问题描述】:

如果模型状态无效,则在 jquery 回发时,我想使用 jquery 不显眼的验证来显示验证错误消息。我创建了一个示例应用程序。应用中的viewmodel如下

 public class CityModel
{
    public int Id { get; set; }

    [Display(Name = "City")]
    [Required(ErrorMessage = "City is required")]
    public string City { get; set; }
}

并且控制器有以下动作方法

 public ActionResult City()
    {
        var cities = GetCities();

        return View(cities);
    }

    [HttpPost]
    public ActionResult SaveCity(CityModel cityModel)
    {
        if (ModelState.IsValid)
        {
            //Save City
            return null;
        }
        else
        {
            return View();
        }
    }

public List<CityModel> GetCities()
    {
        var citiesList = new List<CityModel>
        {
            new CityModel() {Id = 1, City = "London"},
            new CityModel() {Id = 2, City = "New York"}
        };
        return citiesList;
    }

视图有以下标记

@model List<CityModel>
<h2>Cities</h2>

@Html.ValidationSummary(true)
@using (@Html.BeginForm(null, null, FormMethod.Post, new { id = "frmSite", name = "frmSite" }))
{
@Html.EditorForModel()

<input type="submit" name="Sumbit" onclick=" SaveCity(); return false; " />
}

<script>
function SaveCity() {       
    $.ajax({
        type: "POST",
        url: "/Home/SaveCity",
        contentType: "application/html; charset=utf-8",
        data: {
            Id: $('.cityId').val(),
            City: $('.cityName').val()
        },
        success: function (data) {
        }

    });
}   
 </script>

编辑器模板看起来像

@model CityModel
<table class="table">
    <tr>
        <td>
            @Html.TextBoxFor(x => x.Id, new {@class = "cityId"})
        </td>
    </tr>
    <tr>
        <td>
            @Html.TextBoxFor(x => x.City, null, new {@class = "cityName"})
            @Html.ValidationMessageFor(x => x.City)
        </td>
    </tr>
</table>

我已经检查了&lt;script src="/Scripts/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/jquery.validate.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/jquery.validate.unobtrusive.js"&gt;&lt;/script&gt; 是否包含在页面中,&lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt; 是否存在于网络配置文件中

【问题讨论】:

  • 您是否在表单中设置了@Html.ValidationSummary(true)
  • 是的。它设置为 true
  • 不是content: "application/html; charset=utf-8",应该是contentType:"application/json; charset=utf-8"
  • @Jai 是的。我改变了它,但这没有任何区别。我在 action 方法中获取模型中的数据。也更新了问题。
  • 您是否在表单中有字段,因为如果字段存在于表单中并且您必须像本文中的答案一样验证表单-stackoverflow.com/a/11469666/3748701

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


【解决方案1】:

您正在通过 ajax 调用您的帖子,因此您需要手动调用 $form.validate(); 并使用 $form.valid() 测试结果:

function SaveCity() {

    $.validator.unobtrusive.parse($form);
        $form.validate();
        if ($form.valid()) {

        $.ajax({
            type: "POST",
            url: "/Home/SaveCity",
            contentType:"application/json; charset=utf-8",
            data: {
            Id: $('.cityId').val(),
            City: $('.cityName').val()
            },
            success: function (data) {
            }

        });

    }
}

如果它是纯粹的客户端,错误将包含在 jquery 验证对象$form.validate().errorList 中,但您必须进行一些类似于我在下面提到的手动处理。

如果您希望返回服务器端模型状态,您可以将模型状态错误添加为控制器中的键值对,并将它们作为 json 返回。

您可以使用下面的方法来显示消息。

这会找到所有带有模型状态错误键的验证消息,并将红色错误消息添加到它们。请注意,您可能希望对其进行调整以针对一个键显示许多错误消息。

public doValidation(e)
{
        if (e.data != null) {
            $.each(e.data, function (key, value) {
                $errorSpan = $("span[data-valmsg-for='" + key + "']");
                $errorSpan.html("<span style='color:red'>" + value + "</span>");
                $errorSpan.show();
            });
        }
}

更新

这是上面改编的,因此您可以从 jquery 不显眼的错误中手动解析它:

        $.each($form.validate().errorList, function (key, value) {
            $errorSpan = $("span[data-valmsg-for='" + value.element.id + "']");
            $errorSpan.html("<span style='color:red'>" + value.message + "</span>");
            $errorSpan.show();
        });

只需在 else 语句中弹出它就可以了。 :)

【讨论】:

  • 完美@hutchonoid。非常感谢!
  • @Learner 没问题,我也会向您展示如何解析返回的内容。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 2011-10-18
  • 2021-02-09
相关资源
最近更新 更多