jQuery的岗位和不显眼AJAX验证工作不MVC 4 [英] Jquery post and unobtrusive ajax validation not working mvc 4

查看:217
本文介绍了jQuery的岗位和不显眼AJAX验证工作不MVC 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery的回发如果模型状态无效我要显示使用jquery不显眼的验证验证错误消息。我创建了一个示例应用程序。在应用程序的视图模型是如下

On the jquery postback if the model state is invalid I want to show the validation error messages using jquery unobtrusive validation. I have created a sample application. The viewmodel in the application is as below

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

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

和控制器具有以下行为方法

and the controller has the following action methods

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

的意见有以下的加价

The views have the following mark ups

@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;脚本的src =/脚本/ jQuery的-1.10.2.js&GT;&LT; / SCRIPT&GT; &LT;脚本的src =/脚本/ jquery.validate.js&GT;&LT; / SCRIPT&GT; &LT;脚本的src =/脚本/ jquery.validate.unobtrusive.js&GT;&LT; / SCRIPT&GT; 包括在网页和&LT;添加键=UnobtrusiveJavaScriptEnabled 值=真/&GT; 是present在Web配置文件

I have checked the <script src="/Scripts/jquery-1.10.2.js"></script> <script src="/Scripts/jquery.validate.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.js"></script> are included in the page and <add key="UnobtrusiveJavaScriptEnabled" value="true" /> is present in the web config file

推荐答案

正在呼吁通过AJAX您的文章,所以你需要手动调用 $ form.validate(); 和测试结果与 $ form.valid()

You are calling your post via ajax so you will need to manually call $form.validate(); and test the result with $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 但你必须做一些手工处理类似我提以下。

If it is purely client-side, the errors will be contained within the jquery validation object $form.validate().errorList but you will have to do some manual processing similar to what I mention below.

如果您希望返回服务器端模式状态下,你可以添加模型的状态误差为键值对在你的控制器,并将其返回为JSON。

If you wish to return server-side model state you can add the model state errors as a key value pair in your controller and return them as json.

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

You can use the below method to display the messages.

这个发现与模型状态误差项的所有验证消息跨越,并增加了红色的错误信息给他们。请注意,您可能要适应这对关键显示很多的错误信息。

This finds all the validation message spans with model state error keys and adds the red error message to them. Please note you may want to adapt this to display many error messages against a key.

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不显眼的错误,而不是解析:

Here is the above adapted so you can parse it manually from the jquery unobtrusive errors instead:

        $.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语句,你是好去。 :)

Just pop that in an else statement and you are good to go. :)

这篇关于jQuery的岗位和不显眼AJAX验证工作不MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆