我是ASP.NET MVC的新手,正在嘗試驗證文本框。基本上,如果用戶輸入少於2或非數字,我如何得到錯誤顯示。這裏是我試圖遵循的tutorial。如何驗證ASP.NET MVC中的文本框
下面我有我的代碼。
創建視圖:
<%= Html.ValidationSummary()%>
<%= using (HtmlBeginForm()){%>
<div class="half-col">
<label for="Amount">Amount:</label>
<%= Html.TextBox("Amount")%>
<%= Html.ValidationMessage("Amount", "*")%>
</div>
創建控制器:
[AcceptVerbs (HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude ="ID")] Charity productToCreate)
{
//Validation
if (productToCreate.Amount < 2)
ModelState.AddModelError("Amount, Greater than 2 please");
return View(db.Donations.OrderByDescending(x => x.ID).Take(5).ToList()); //Display 5 recent records from table
}
型號:
public class Charity
{
public int ID { get; set; }
public string DisplayName { get; set; }
public DateTime Date { get; set; }
public Double Amount { get; set; }
public Double TaxBonus { get; set; }
public String Comment { get; set; }
}
錯誤:
CS1501 No overload for method 'AddModelError' takes 1 CharitySite
在MVC中,您不驗證文本框,而是驗證模型。文本框與模型屬性相關聯,如果模型的這些屬性不驗證,則顯示與該屬性的文本框相關聯的錯誤。 –
你爲什麼從2009年開始接受教程?如果你想學習asp.net MVC,請學習最新版本。 – ataravati