2013-07-07 52 views
10

我有剃刀文件,我定義的HTML表單文本框的字符串:MVC無法驗證空字符串

@using (Html.BeginForm()) { 
     @Html.ValidationSummary(true) 
     <fieldset> 
     <legend>Product</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Name) 
      @Html.ValidationMessageFor(model => model.Name) 
     </div> 
     <p> 
      <input type="submit" value="Create" /> 
     </p> 
     </fieldset> 
    } 

的問題是,我想這個字段(model.name)不被空的,但剃刀驗證允許字符串爲空,當我添加空字符串模型時會給出錯誤。 任何建議如何驗證只是這個字符串不再是空的了?

回答

5

那麼你的視圖模型是什麼樣子?

您可以在視圖模型一個DataAnnotation屬性添加到您的Name屬性:

public class MyViewModel 
{ 
    [Required(ErrorMessage="This field can not be empty.")] 
    public string Name { get; set; } 
} 

然後,在你的控制器,你可以檢查張貼的模式是否是有效的。

public ActionResult MyAction(ViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     //ok 
    } 
    else 
    { 
     //not ok 
    } 
}