面对问题,同时显示使用无碍JQuery的局部图的错误信息 [英] Facing issue while showing the error messages in Partial View using unobstructive JQuery

查看:102
本文介绍了面对问题,同时显示使用无碍JQuery的局部图的错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我地区MVC3

Following is my Area in MVC3

型号

public class AdminModule
{
    [Display(Name = "My Name")]
    [Required]
    public String MyName { get; set; }
}

管窥

@model _1.Areas.Admin.Models.AdminModule
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
    @Html.LabelFor(i => i.MyName)
    @Html.TextBoxFor(i => i.MyName)
    @Html.ValidationMessageFor(i => i.MyName)
    <p id="getDateTimeString">
    </p>
    <input type="submit" value="Click here" id="btn" />
}

<script language="javascript" type="text/javascript">
    $('#btn1').click(function () {
        debugger;
        var $form = $("#myForm");

        // Unbind existing validation
        $form.unbind();
        $form.data("validator", null);

        // Check document for changes
        $.validator.unobtrusive.parse(document);

        // Re add validation with changes
        $form.validate($form.data("unobtrusiveValidation").options);

        if ($(this).valid()) {
            var url = '@Url.Action("Index_partialPost", "Admin", 
                                                new { area = "Admin" })';
            $.post(url, null, function (data) {
                alert(data);
                $('#myForm').html(data);
            });
        }
        else

        return false;
    });
</script>

控制器动作

[HttpPost]
public ActionResult Index_partialPost(AdminModule model)
{
    return PartialView("_PartialPage1", model);
} 

[HttpGet]
public ActionResult Index_partial()
{
    return PartialView("_PartialPage1");
}

每当我提交表单和叶所需的字段为空。它关系到服务器,我认为。我查了这里......

我的困惑是 =>如何修改我下面提到code $使用.post的显示在客户端模型中提到的相同的验证消息?

My confusion is => How can I modify my below mentioned code to display the same validation messages mentioned in model at client end using $.post ?

推荐答案

您可以使不显眼的客户端验证。通过添加下面的脚本引用启动:

You could enable unobtrusive client side validation. Start by adding the following script reference:

<script type="text/javascript" src="@Url.Content("~/scripts/jquery.validate.unobtrusive.js")"></script>

和则:

@model _1.Areas.Admin.Models.AdminModule
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
    @Html.LabelFor(i => i.MyName)
    @Html.TextBoxFor(i => i.MyName)
    @Html.ValidationMessageFor(i => i.MyName)
    <p id="getDateTimeString"></p>
    <input type="submit" value="Click here" />
}

<script type="text/javascript">
    $('#myForm').submit(function () {
        if ($(this).valid()) {
            $.post(this.action, $(this).serialize(), function(data) {
                $('#myForm').html(data);

                $('#myForm').removeData('validator');
                $('#myForm').removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse('#myForm');
            });
        }
        return false;
    });
</script>


更新:

现在,你通过电子邮件发给我你的实际code我看到有一个地狱很多与它的问题。而不是通过所有的人都去我preFER完全重写一切从头开始。

Now that you sent me your actual code by email I see that there are a hell lot of a problems with it. Instead of going through all of them I prefer to completely rewrite everything from scratch.

于是我们开始由〜/地区/行政/查看/共享/ _LayoutPage1.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        <ul>
            <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
        </ul>
        @RenderBody()
    </div>
    <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>

注意我是如何感动了所有脚本文件的底部,以及增加了一个专门负责部分,在那里自定义脚本将被放置。

Notice how I moved all scripts to the bottom of the file as well as added a specifically dedicated section where custom scripts will be placed.

接下来,我们移动到〜/地区/行政/查看/管理/ Index.cshtml

@model _1.Areas.Admin.Models.AdminModule
@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}

<div id="formContainer" data-url="@Url.Action("Index_partial", "Admin", new { area = "Admin" })"></div>
<input id="BTN" type="button" value="Button" />

@section Scripts {
    <script type="text/javascript" src="@Url.Content("~/areas/admin/scripts/myscript.js")"></script>
}

在这里,你可以看到,我已经取代了按钮的类型从提交按钮,因为这个按钮未包含在表单中提交。我也摆脱了在&LT; P&GT; ID =myForm会这是不是是具有元素不但无益,而且你在你的DOM是无效的标记重复的ID被结束了。我还使用了数据网址 HTML5属性在容器div来表示服务器端脚本将加载形式的URL。而我在这个文件中所做的最后一件事是覆盖脚本我们有一个自定义脚本先前在布局定义的部分。

Here you could notice that I have replaced the type of the button from submit to button because this button is not contained within a form to submit. I have also gotten rid of the <p> element you were having with id="myForm" which was not only useless but you were ending up with duplicate ids in your DOM which is invalid markup. I have also used the data-url HTML5 attribute on the container div to indicate the url of the server side script that will load the form. And the last thing I did in this file was to override the scripts section we defined earlier in the Layout with a custom script.

所以,接下来的部分是自定义脚本:〜/区域/管理/脚本/ myscript.js

So the next part is the custom script: ~/areas/admin/scripts/myscript.js:

$('#BTN').click(function () {
    var $formContainer = $('#formContainer');
    var url = $formContainer.attr('data-url');
    $formContainer.load(url, function () {
        var $form = $('#myForm');
        $.validator.unobtrusive.parse($form);
        $form.submit(function () {
            var $form = $(this);
            if ($form.valid()) {
                $.post(this.action, $(this).serialize(), function (data) {
                    $form.html(data);
                    $form.removeData('validator');
                    $form.removeData('unobtrusiveValidation');
                    $.validator.unobtrusive.parse($form);
                });
            }
            return false;
        });
    });
    return false;
});

pretty标准code在这里。我们订阅按钮的Click事件,并使用AJAX调用加载部分。只要做到这一点,我们指导不显眼的验证框架到新添加的内容解析到我们的DOM。下一步是通过订阅 .submit 事件AJAXify形式。而由于在成功的处理程序,我们再次更换容器的内容,我们需要指示不引人注目的验证框架来分析新的内容。

Pretty standard code here. We subscribe to the click event of the button and load the partial using an AJAX call. As soon as this is done we instruct the unobtrusive validation framework to parse the newly added contents to our DOM. The next step is to AJAXify the form by subscribing to the .submit event. And because in the success handler we are once again replacing the contents of the container we need to instruct the unobtrusive validation framework to parse the new contents.

和最后部分:

@model _1.Areas.Admin.Models.AdminModule

@using (Html.BeginForm("Index_partialPost", "Admin", FormMethod.Post, new { id = "myForm" }))
{
    @Html.LabelFor(i => i.MyName)
    @Html.TextBoxFor(i => i.MyName)
    @Html.ValidationMessageFor(i => i.MyName)
    <p id="getDateTimeString"></p>
    <input type="submit" value="Click here" />
}

在这里,你可以看到,我已经摆脱了JavaScript的绝对任何痕迹。 JavaScript的属于单独的文件。它有没有什么意见做。你不应该混合标记和脚本。当你有单独的脚本不仅动态标记会小很多,但你也可以利用的东西像浏览器缓存的外部脚本,缩小,......你将在这个部分需要注意的另一件事是,我删除&LT;脚本&gt;在你被引用的jQuery和jQuery.validate脚本节点。你已经做了,在布局,不重复了两遍。

Here you could notice that I have gotten rid of absolutely any traces of javascript. javascript belongs to separate files. It has nothing to do in views. You should not mix markup and scripts. When you have separate scripts not only that your dynamic markup will be much smaller but also you could take advantage of things like browser caching for the external scripts, minification, ... Another thing you will notice in this partial is that I remove the <script> nodes in which you were referencing jQuery and the jQuery.validate scripts. You already did that in the Layout, do not repeat it twice.

这篇关于面对问题,同时显示使用无碍JQuery的局部图的错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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