ASP.Net MVC 2 - jQuery验证和表单提交 - DataAnnotations

时间:2010-08-05 19:32:23

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

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

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

问题:

  1. 此处未发生客户端验证。
  2. 如何使$(form).submit遵守jquery验证,如果没有,则不发布数据?我可以在发布(手动)之前检查文本框是否为空,但我想使用正确的方法。
  3. 这个相同的示例适用于MSAjax和验证,没有任何问题。

    Master Page Head

    <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 on View - Index

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

    由于

4 个答案:

答案 0 :(得分:0)

我建议你做一些我所描述的事情here

答案 1 :(得分:0)

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

这是如何使其与验证摘要一起使用,但也许它可以帮助您找出问题所在。我知道如果你引用微软验证javascript和jquery验证javascript文件,它们会引起彼此的问题。

答案 2 :(得分:0)

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

Simple but powerful jquery form validation

...问候

答案 3 :(得分:0)

&lt;%using(Html.BeginForm(“Register”,“User”,FormMethod.Post,new {id =“RegisterForm”}))

 $("#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"
                }
            }
        });