2015-02-06 28 views
7

我有一個MVC 5應用程序,我使用數據註釋來做大部分驗證。一個在我的類中的屬性看起來是這樣的:MVC5 - 數據註釋 - 客戶端驗證沒有發生?

[Required(ErrorMessage = "Please enter a business name")] 
[StringLength(80)] 
public string BusinessName { get; set; } 

的驗證工作,但就像我認爲應該不會出現在瀏覽器中發生的事情。在我的頁面上,我有一個保存按鈕。如果我離開了公司名稱字段爲空,然後單擊保存,後做是爲了看起來,部分控制器方法,如下所示:

[HttpPost] 
    public ActionResult Create(Advertiser advertiser, FormCollection collection, HttpPostedFileBase file) 
    { 
     // Before we do anything, let's check to make sure any validation that's already been done is clean. 
     if (!ModelState.IsValid) 
     { 
      return View(advertiser); 
     } 
    ... 
    ... 
} 

當執行這種方法,模型的狀態已被設置爲無效。這很好,因爲它是無效的,因爲商業名稱字段爲空。但是,這種驗證不應該發生在客戶端嗎?

在我的.cshtml文件中的字段如下所示(使用引導程序):

<div class="form-group"> 
    @Html.Label("Business Name", new { @class = "control-label col-md-3" }) 
    <div class="col-md-9"> 
     @Html.TextBoxFor(model => model.BusinessName, new { @class = "form-control", title = "", autofocus = true }) 
     @Html.ValidationMessageFor(model => model.BusinessName) 
    </div> 
</div> 

我的web.config正確設置如下:

<appSettings> 
    <add key="webpages:Version" value="3.0.0.0" /> 
    <add key="webpages:Enabled" value="false" /> 
    <add key="ClientValidationEnabled" value="true" /> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 
    </appSettings> 
+0

什麼是您的cshtml標記? (你的看法...什麼是代碼) – 2015-02-06 12:57:28

+0

@Ahmedilyas - 我修改了我的帖子以添加標記。的[MVC3客戶端驗證不工作] – 2015-02-06 12:59:18

+0

可能重複(http://stackoverflow.com/questions/4706174/mvc3-client-side-validation-not-working) – 2015-02-06 13:01:46

回答

10

,我發現我的問題。在我BundleConfig.cs我有以下幾點:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
       "~/Scripts/jquery-{version}.min.js", 
       "~/Scripts/jquery-ui-1.10.4.min.js", 
       "~/Scripts/jquery.base64.js" 
       )); 

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
       "~/Scripts/jquery.validate.min.js", 
       "~/Scripts/jquery.validate.unobtrusive.min.js" 
       )); 

但是,我沒想到的是,jqueryval束沒有得到默認情況下在_Layout.cshtml文件加載。所以我需要添加它,如下所示:

@Scripts.Render("~/bundles/jquery") 
@Scripts.Render("~/bundles/jqueryval") 
@Scripts.Render("~/bundles/bootstrap") 
@RenderSection("scripts", required: false) 

一旦我這樣做了,它就像它應該那樣工作。當然,這會導致它爲所有頁面加載。這可能並不理想。如果不是,則根據需要在每個頁面中分別加載它。

相關問題