2014-01-09 24 views
0

我有一個問題來驗證ASP.Net MVC中的窗體。我粘貼了ViewsModel我已經用過,這樣可以幫助你找到我做錯的地方。如何正確驗證ASP.NET MVC?

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('[email protected](Model.OrderID)', '@Model.ActionName','[email protected](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

+2

究竟是什麼問題?它沒有在C#或JavaScript中驗證嗎? –

+0

沒關係。只要找出[[必須]]屬性,如果我們通過'onclick'提交表單,則不起作用。 – Lakhae

回答

0

我們增加一個檢查

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

做這種方式所需的屬性不工作。希望這可以幫助