Asp.net

將 Twitter Bootstrap 與 Asp.net MVC 3 表單集成

  • June 16, 2012

我正在使用 Asp.net MVC 3 和 Twitter Bootstrap。我想要的是整合它們。對我來說最大的問題是表格。我正在使用HtmlHelper它,這是一個問題,當涉及到驗證時,我希望它生成這樣的 HTML:

<div class="control-group error">
  <label for="field" class="control-label">OMG this label is so awesome: </label>
  <div class="controls">
     <input type="text" name="field" id="field" value="yeah" />
     <span class="help-inline">Eventually some error :C</span>
  </div>
</div>

這是我的 HtmlHelper 程式碼:

@Html.LabelFor(x => x.Field)
@Html.EditorFor(x => x.Field)
@Html.ValidationMessagesFor(x => x.Field)

問題是我希望僅在此欄位上確實存在錯誤時才設置最外層 div 上的類錯誤。另一個問題是我不知道如何強制使用 span 標籤來處理錯誤。我可以在 HtmlHelper 中編寫我的方法,但它會讓我重新實現幾乎所有的LabelFor,EditorForValidationMessageFor. 有沒有更簡單的方法來做到這一點?那麼不顯眼的驗證呢?

我遇到了同樣的挑戰,並且在標籤方面得到了一些幫助(見下文),這就是我得到的:

<div class="control-group @if (!ViewData.ModelState.IsValidField("Name")) { @Html.Raw("error"); }">
   @Html.LabelFor(model => model.Name, new {@class = "control-label"})
   <div class="controls">
       @Html.EditorFor(model => model.Name)
       @Html.ValidationMessageFor(model => model.Name, null, new {@class = "help-inline"})
   </div>
</div>

Html.LabelFor實施:https ://stackoverflow.com/a/6722082

我沒有嘗試不顯眼的驗證,但似乎你只需要啟動它。

如果你正在尋找一個全域錯誤,你應該使用類似的東西:

@if (ViewData.ModelState.IsValid == false) {
   <div class="alert alert-error"><button class="close" dismiss="alert">x</button><!-- some text--></div>
}

這裡有一個活生生的例子(法語)http ://ws.sherbrow.fr/auth

整個項目的原始碼應該很快就會提供(請參閱我的個人資料 - 或直接詢問我)。

引用自:https://stackoverflow.com/questions/11065442