如何在ASP.NET MVC中正确验证?

时间:2014-01-09 17:06:10

标签: jquery asp.net-mvc-4

我在ASP.Net MVC中验证表单时遇到问题。我已粘贴ViewsModel我已经使用过,以便它可以帮助您找到我做错的地方。

View

@using(Html.BeginForm(@Model.ActionName, "Home", FormMethod.Post, new { id = "form" + Model.OrderID, enctype = "application/json" }))
{
    <h3 style="margin: 15px">@Model.DisplayName</h3>
    @Html.HiddenFor(model=>model.OrderID)

    <div>
        <div style="margin: 0px 0px 5px 20px; width:500px;">
            Month: @Html.TextBoxFor(m => m.Month, new { title = "Value", style = "margin: 10px 40px 0 20px; width: 30px;" })
                    @Html.ValidationMessageFor(m => m.Month,"*")
            Year: @Html.TextBoxFor(m => m.Year, new { title = "Value", style = "margin: 10px 40px 0 20px; width: 30px;" })
                    @Html.ValidationMessageFor(m => m.Year,"*")
            <button class="ui-button ui-button-report-text" style="margin: 0 0 0 40px" onclick="getOrder('form@(Model.OrderID)', '@Model.ActionName','order@(Model.OrderID)'); return false;">Get Order</button>
        </div>
    </div>
}

Model

    [Required(AllowEmptyStrings = false)]
    public int Month { get; set; }

    [Required(AllowEmptyStrings = false)]
    public int Year { get; set; }

仅供参考,我使用onclick提交表单。

TIA

1 个答案:

答案 0 :(得分:0)

我们添加支票

if($('form').valid()){
    //ajax call
}else{
    var $validator = $('form').validate();
    //show errors/validation
}

这样做所需的属性确实有效。希望这有助于