【问题标题】:ASP.Net MVC 2 - jQuery Validation and Form Submit - DataAnnotationsASP.Net MVC 2 - jQuery 验证和表单提交 - DataAnnotations
【发布时间】:2011-03-26 00:15:23
【问题描述】:

我有一个示例应用程序,试图在这个场景中学习 jQuery 验证和提交表单。

页面有一个文本框(每个信封类的信封ID)。如果单击提交按钮并且文本框为空,那么我想显示一条错误消息。如果它不为空,那么我想将 ajax 请求发布到 GetData Action。该操作返回部分视图(值 1 或 2)或错误字符串。

问题:

  1. 此处未进行客户端验证。
  2. 我怎样才能让$(form).submit 遵守jquery 验证,如果为空则不发布数据?我可以在发布之前(手动)检查文本框是否为空,但我想使用正确的方式。

同样的例子适用于 MSAjax 和验证,没有任何问题。

母版页标题

<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery.validate.min.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/MicrosoftMvcJQueryValidation.js") %>"></script>

类:

namespace PartialViews.Models
    {
        public class Envelope
        {
            [Required(ErrorMessage="Envelope ID is required!")]
            public string EnvelopeID { get; set; }
        }
    }

数据操作:

[HttpPost]
public ActionResult GetData(Envelope envelope)
{
    ActionResult result = null;
    if (ModelState.IsValid)
    {
        Information myInfo = newInformation();
        if (envelope.EnvelopeID == "1")
        {
            result = View("TQ1PV", myInfo); //partial view
        }
        elseif (envelope.EnvelopeID == "2")
        {
            result = View("TQ2PV", myInfo); //partial view
        }
        else
        {
            result = Content("Error");
        }
    }
    else
    {
        result = View("index", envelope);
    }
    return result;
}

索引操作:

public Action Result Index()
{
    return View();
}

视图上的 JS - 索引

<script type="text/javascript">
    $(function () {
        //onload 
        $("#evid").focus();
        $("form[name='EVIDForm']").submit(function () {
            var action = $(this).attr('action');
            var evid = $("#evid").val();
            var tdata = $(this).serialize();
            alert(tdata);
            $message = $("#resultDiv");
            $message.html('').removeClass("red");
            $.ajax({
          cache: false, 
          type: "post",
          url: action,
          data: tdata,
          dataType: "html",
          error: function (xhr, ajaxOptions, thrownError){ 
                    alert('system error');
                },
                success: function(data){
           if (data == 'Error')
                        $message.html("No such EV ID found!").addClass("red");
                    else
                        $message.html(data);
          }
         });
            return false;
        });
    });

</script>

视图上的 HTML - 索引:

    <% Html.EnableClientValidation(); %>
    <%= Html.ValidationSummary() %>

    <% using (Html.BeginForm("GetData", "Info", FormMethod.Post, new {name = "EVIDForm" }))
       {%>
       <%= Html.LabelFor(model => model.EnvelopeID) %> &nbsp;&nbsp;
       <%= Html.TextBoxFor(model => model.EnvelopeID, new { maxlength = "8"})%>
       <%= Html.ValidationMessageFor(model => model.EnvelopeID,"*") %>
       <br /><br />


        Correct EVIDs are 1 and 2. All other entries will result in an error.
        <br /><br />
        <input type="submit" value="submit" />
    <%} %>
    <div id="resultDiv" style="margin-top: 20px;"></div>

谢谢

【问题讨论】:

  • 我遇到了与@vandalo 链接的帖子中描述的几乎相同的问题。如果不提交表单,客户端验证似乎不起作用。但是如果我必须提交表单,则验证不再是客户端......我在这里没有收到我的问题的答案:http://stackoverflow.com/questions/4172319/inline-client-side-validation-with-mvc-and-jquery/
  • @Lorenzo:表单未提交。您可以尝试在接收帖子的控制器中设置断点。它永远不会触发。唯一的问题是(只有第一次,直到你不点击按钮)客户端验证似乎并没有从一开始就触发。
  • @vandalo:如果你使用 fiddler 或 firebug,你可以看到提交到服务器

标签: jquery validation asp.net-mvc-2 data-annotations


【解决方案1】:

我建议你做我描述过的事情here

【讨论】:

    【解决方案2】:

    http://geekswithblogs.net/stun/archive/2010/02/27/asp.net-mvc-client-side-validation-summary-with-jquery-validation-plugin.aspx

    如果您想查看完整的 javascript,我将我的版本发布在我发布的问题中,我发布了 jquery.validate lost on ajax replacement and only showing last error

    这是使它与验证摘要一起使用的方法,但也许它可以帮助您找出问题。我确实知道,如果您引用 microsoft 验证 javascript 和 jquery 验证 javascript 文件,它们会相互导致问题。

    【讨论】:

      【解决方案3】:

      也许您可以使用它来验证所有输入字段:

      Simple but powerful jquery form validation

      问候...

      【讨论】:

        【解决方案4】:

         $("#RegisterForm").validate({
        
                    rules: {
                        ignore: ":not(:visible)",
                        EmailAddress: {
                            required: true,
                            email: true
                        },
                        ConfirmEmailAddress: {
                            required: true,
                            email: true,
                            equalTo: "#EmailAddress"
                        },
                        Password: {
                            required: true
                        },
                        ConfirmPassword: {
                            required: true,
                            equalTo: "#Password"
                        }
                    },
                    messages: {
                        EmailAddress: {
                            required: " Email Address is required",
                            email: " Email Address is invalid"
                        },
                        ConfirmEmailAddress: {
                            required: " Email Address is required",
                            email: " Email Address is invalid",
                            equalTo: "Enter Email Address same as above"
                        },
                        Password: {
                            required: " Password is required"
                        },
                        ConfirmPassword: {
                            required: " Password is required",
                            equalTo: " Enter Confirm Password same as above"
                        }
                    }
                });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-09
          • 2021-09-08
          • 2018-06-12
          • 1970-01-01
          相关资源
          最近更新 更多