简体   繁体   English

Jquery 帖子和不显眼的 ajax 验证不起作用 mvc 4

[英]Jquery post and unobtrusive ajax validation not working mvc 4

On the jquery postback if the model state is invalid I want to show the validation error messages using jquery unobtrusive validation.在 jquery 回发上,如果模型状态无效,我想使用 jquery 非侵入式验证显示验证错误消息。 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>

And the editor template looks like编辑器模板看起来像

@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>

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我检查了<script src="/Scripts/jquery-1.10.2.js"></script> <script src="/Scripts/jquery.validate.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.js"></script>包含在页面中并且<add key="UnobtrusiveJavaScriptEnabled" value="true" />存在于 web 配置文件中

You are calling your post via ajax so you will need to manually call $form.validate();您正在通过 ajax 调用您的帖子,因此您需要手动调用$form.validate(); and test the result with $form.valid() :并使用$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) {
            }

        });

    }
}

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

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.如果您希望返回服务器端模型状态,您可以将模型状态错误作为键值对添加到控制器中,并将它们作为 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();
            });
        }
}

Updated更新

Here is the above adapted so you can parse it manually from the jquery unobtrusive errors instead:这是上面的改编,因此您可以从 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();
        });

Just pop that in an else statement and you are good to go.只需在 else 语句中弹出它,你就可以开始了。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM