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

发布于 2024-09-13 06:18:25 字数 3668 浏览 5 评论 0原文

我有一个示例应用程序,试图在这个场景中学习 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>

谢谢

I have a sample application, trying to learn jQuery validation and submit form in this scenerio.

The page has one text box (EnvelopeID per class Envelope). If submit button is clicked and the text box is empty then i want to show an error message. If it is not empty then i want to post ajax request to GetData Action. The action returns partial views (value 1 or 2) or error string.

Problem:

  1. Client validation is not happening here.
  2. How can i make $(form).submit to adhere to jquery validation and not post the data if empty? I can check for text box being empty or not before posting (manually) but i want to use the proper way.

This same very example works with MSAjax and validation without any problem.

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>

Class:

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

Data Action:

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

Index Action:

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

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

    <% using (Html.BeginForm("GetData", "Info", FormMethod.Post, new {name = "EVIDForm" }))
       {%>
       <%= Html.LabelFor(model => model.EnvelopeID) %>   
       <%= 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>

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

触ぅ动初心 2024-09-20 06:18:25

我建议您执行我在此处

I would suggest you to do something I've described here

追我者格杀勿论 2024-09-20 06:18:25

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

和如果您想查看完整的javascript,我在我发布的问题中发布了我的版本 jquery.validate 在 ajax 替换时丢失并且仅显示最后一个错误

这是如何使其与验证摘要一起工作,但也许它可以帮助您找出问题。我确实知道,如果您引用 microsoft 验证 javascript 和 jquery 验证 javascript 文件,它们将导致彼此出现问题。

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

And if you want to see the full javascript, I have my version posted in a question I posted jquery.validate lost on ajax replacement and only showing last error

This is how to make it work with the validation summary, but perhaps it can help you figure out your problem. I do know that if you are referencing the microsoft validation javascript and the jquery validation javascript files, they will cause issues with one another.

吾家有女初长成 2024-09-20 06:18:25

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

简单但强大的 jquery 表单验证

问候...

Maybe you can use this for validate all input fields:

Simple but powerful jquery form validation

Regards...

不甘平庸 2024-09-20 06:18:25

<% 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"
                }
            }
        });

<% 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"
                }
            }
        });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文