Asp.net

EditorFor 的最小值和最大值

  • January 6, 2016

我一直在嘗試這段程式碼來設置我的最小值和最大值EditorFor

<label id="LbStartYear" style="width: 200px">From Date: @Html.EditorFor(model => model.SelectedYearBegin, new { htmlAttributes = new { @min = "0", @max = "20" } })</label>

但沒有成功。永遠不會設置最小值和最大值。0我嘗試從and中刪除引號20,也嘗試使用和不使用@.

有任何想法嗎?

只需Range在模型屬性上使用 DataAnnotation 屬性。通過使用此屬性,您可以限制使用者輸入不屬於該範圍的任何其他數字。

導入以下命名空間 -

using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

然後用屬性裝飾你的財產Range-

[Range(0,20)]
public int SelectedYearBegin { get; set; }

有關範圍屬性的更多資訊 - https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute(v=vs.110).aspx

您可以通過在 Web.config 中啟用它來獲得客戶端驗證 -

<add key="ClientValidationEnabled" value="true"/> 
<add key="UnobtrusiveJavaScriptEnabled" value="true"/> 

確保連結 JQuery 不顯眼並驗證 JS 文件。

或者,如果您仍想設置minand maxfor EditorFor,那麼您需要獲得 MVC 5.1 或更高版本。下面的程式碼適用於 MVC 5.1 及更高版本。

@Html.EditorFor(model => model.SelectedYearBegin, new { htmlAttributes = new { @min = "0", @max = "20" } })

如果您不想使用 MVC 5.1 及更高版本,則只需使用TextBoxFor-

@Html.TextBoxFor(model => model.SelectedYearBegin, new { type = "number", min = 0, max = 100 })

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