jQuery验证无法正常工作

时间:2015-08-09 06:16:14

标签: jquery asp.net-mvc-5

我有一个简单的联系表格,电子邮件,第一个&姓氏,主题和信息。我有标准的MVC 5验证设置,它有点工作(我使用jQuery ajax提交表单,如果这有所不同)。如果我将表单保留为空并单击发送,则会显示所有正确的验证消息,但如果我在列表中填写1 02 2项并单击发送发送邮件,丢失信息的1/2。

我可以显示您想要查看的任何代码但是现在我将从视图,jQuery和电子邮件视图模型开始。

ContactEmail.cs

using AccessorizeForLess.ViewModels;
using Postal;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace AccessorizeForLess.Models
{
    public class ContactEmail : Email
    {
        public string To { get; set; }

        [DataType(DataType.EmailAddress)]
        [DisplayName("Email Address")]
        [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Please enter a valid email address!")]
        [Required(ErrorMessage="Please provide your email address")]
        public string From { get; set; }

        [DisplayName("First Name")]
        [Required(ErrorMessage="Please provide your first name")]
        public string FirstName { get; set; }

        [DisplayName("Last Name")]
        [Required(ErrorMessage="Please provide your last name")]
        public string LastName { get; set; }

        [DisplayName("Subject")]
        [Required(ErrorMessage="Please select a subject")]
        public string SelectedSubject { get; set; }

        [DisplayName("Message")]
        [DataType(DataType.MultilineText)]
        [Required(ErrorMessage="Please provide a message for the email")]
        public string Message { get; set; }

        public List<EmailSubjectViewModel> Subjects { get; set; }
    }
}

我的观点:

@model AccessorizeForLess.Models.ContactEmail
@{
    ViewBag.Title = "Contact";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Contact</h2>
@using (Html.BeginForm("SendAJAX", "Contact", FormMethod.Post, new { @id = "sendContactForm" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>
            AccessorizeForLess.net&nbsp;&nbsp;&nbsp;
            <a href="https://www.facebook.com/accessorize5orless" target="_blank" title="Accessorize For Less On Facebook"><img src="~/Content/icon-facebook.png" /></a>
        </h4>
        <div id="sending" style="display:none;"><img src="~/Content/ajax-loader.gif" /></div>
        <div style="color:red" id="MessageSent"></div>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.From, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.From, new { @id = "from" })
                @Html.ValidationMessageFor(model => model.From)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName)
                @Html.ValidationMessageFor(model => model.LastName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.SelectedSubject, "Category", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SelectedSubject, new SelectList(Model.Subjects, "Id", "Subject"), "- Please Select -")
                @Html.ValidationMessageFor(model => model.SelectedSubject)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Message, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Message, new { @cols = "25", @rows = "55" })
                @Html.ValidationMessageFor(model => model.Message)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Send" class="btn btn-default" id="SendMessage" />
            </div>
        </div>
    </div>
}

我的jQuery:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#sendContactForm").submit(function (e) {
                //alert("Clicked!");
                //prevent Default functionality
                e.preventDefault();

                $("#SendMessage").attr("disbled", true);
                $("#SendMessage").prop("value", "Sending...");
                $("#sending").css("display", "block");
                $("#MessagdSent").html("&nbsp;");

                //get the action-url of the form
                var $form = $(e.target),
                    formData = new FormData(),
                    params = $form.serializeArray()

                $.each(params, function (i, val) {
                    formData.append(val.name, val.value);
                });

                //do your own request an handle the results
                $.ajax({
                    url: $form.attr('action'),
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function (result) {
                        successfulSend(result);
                        resetForm($form)
                    },
                    error: function (result) {
                        failedSend(result);
                    }
                });

                function resetForm(form) {
                    form.find('input:text, input:password, input:file, select, textarea').val('');
                }

                //function that is called when the message is successfully sent
                function successfulSend(result) {
                    //enable the send button
                    $("#SendMessage").attr("disbled", false);

                    //hide the sending gif
                    $("#sending").css("display", "none");

                    //change the text on the button back to Send
                    $("#SendMessage").prop("value", "Send");

                    //set focus to the from email address textbox
                    $("#From").focus();

                    $("#MessageSent").html(result.Message);
                }

                //call this function if for some reason the send fails
                function failedSend(result) {
                    $("#SendMessage").attr("disbled", false);
                    $("#sending").css("display", "none");
                    $("#SendMessage").prop("value", "Send");
                    $("#MessageSent").text(result.ErrorMessage);
                }
            });
        });
    </script>
}

有人可以帮我弄清楚为什么在提供所有必要信息之前它不会继续验证?

1 个答案:

答案 0 :(得分:0)

我在表单上使用.valid()来检查有效性,似乎已经解决了问题。感谢@StephenMuecke的建议。我的新jQuery看起来像这样

a