MVC ModelState.IsValid Ajax 函数

MVC ModelState.IsValid Ajax Function

我有一个 Ajax 函数,当我提交联系表单时它会自动触发,但是我需要阻止该函数触发,除非表单通过模型验证。

Wedding.cs

public class Wedding
{
    [Required]
    [DisplayName("Name")]
    [RegularExpression(@"^(?:.*[a-zA-Z]){1,}$", ErrorMessage = "Name length must be greater than or equal 1 characters and contain letters only.")]

    public String Name { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email Address")]
    [RegularExpression("^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$",ErrorMessage = "Email is not valid")]
    public string EmailAddress { get; set; }

    [Display(Name = "Message")]
    public string Message { get; set; }
}

HomeController.cs

[HttpPost]
public ActionResult Index(FormCollection formCollection, Wedding model)
{
    var name = formCollection["Name"];
    var email = formCollection["EmailAddress"];
    var guestNumber = formCollection["GuestNumber"];
    var events = formCollection["Events"];

    var message = formCollection["Message"];

    ViewBag.Name = name;
    ViewBag.EmailAddress = email;

    if (ModelState.IsValid)
    {
        if (string.IsNullOrEmpty(message))
        {
            _cf.SendEmail("RSVP from " + name, email, "something@ourdomain.com", "This is an email confirmation that " + name + " and " + guestNumber + " guest(s) will be attending " + events + " event(s).", "something@ourdomain.com", true, null, ";");
        }
        else
        {
            _cf.SendEmail("Contact from " + name, email, "something@ourdomain.com", message, "something@ourdomain.com", true, null, ";");
        }
    }

    return View("Index");
}

Index.cshtml

@using (Html.BeginForm(null, null, FormMethod.Post, new {@id = "rsvp_form", role = "form"}))
{
    <div class="rsvp-name">
        <div class="rsvp-formwrap">
            @Html.TextBoxFor(m => m.Name, new {@class = "form-control", @Value = ViewBag.Name, placeholder = "Name", required = "required"})
            <div class="input-border"></div>
        </div>
        <div class="rsvp-formwrap">
            @Html.TextBoxFor(m => m.EmailAddress, new { @class = "form-control", @Value = ViewBag.EmailAddress, placeholder = "Email Address", type = "Email", required = "required" })
            <div class="input-border"></div>
        </div>
    </div>
    <div class="rsvp-guest">
        <label for="GuestNumber" class="lable-guest">Guests</label>
        <div class="rsvp-guestform">
            <div class="guestform">
                <select name="GuestNumber" class="select" id="GuestNumber">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                </select>
            </div>
        </div>
    </div>
    <div class="rsvp-event">
        <div class="rsvp-formwrap">
            <div class="rsvp-eventform">
                <div class="eventform">
                    <select name="Events" class="select" id="event">
                        <option value="All">All Events</option>
                        <option value="Wedding Party">Wedding Party</option>
                        <option value="Wedding Ceremony">Wedding Ceremony</option>
                    </select>
                    <div class="input-border"></div>
                </div>
            </div>
        </div>
    </div>
    <input type="hidden" name="action" value="send_rsvp"/>
    <button type="submit" name="rsvp_submit" class="rsvp-button">I Am Attending</button>
}

$(function(){
    $('#rsvp_form').ajaxForm(function(){
        $('#rsvp_form').slideUp();
        $('.title-rsvp-form').fadeOut( 'slow', function(){
            $(this).fadeIn().html( 'Thank You <br/> Your RSVP has been sent' );
            $(this).animate({
                'margin-top' : '170px'
            });
        });
    });
});


/*-------------------------------------------*/
/*  RSVP AJAX Form Function */
/*-------------------------------------------*/
$(function() {
    // Binding a click event
    // From jQuery v.1.7.0 use .on() instead of .bind()
    $('#contact-button').bind('click', function(e) {
        // Prevents the default action to be triggered. 
        e.preventDefault();
        // Triggering bPopup when click event is fired
       $('.element').bPopup({
            speed: 650,
            fadeSpeed: 'slow',
            transition: 'slideDown'
        });
    });

});

我在表单上有典型的必需占位符元素,但我需要确保遵循正则表达式,目前如果未在相应字段中输入数据,则表单不会提交,但如果输入了数据提交表单,触发 Ajax 函数,然后检查模型状态,当视图重新加载模型验证错误时,Ajax 函数会阻止表单,因此用户看不到需要什么待更正。

如有任何帮助,我将不胜感激:-)

除了上述所有代码外,我还需要将以下脚本添加到我的项目中:

_Layout.cshtml

<script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

web.config

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

现在表单会阻止任何 ModelState 无效的提交,只有当 ModelState 有效时才会显示我的成功消息。