簡體   English   中英

如何在ASP.NET MVC中驗證文本框

[英]How to validate textboxes in ASP.NET MVC

我是ASP.NET MVC的新手,正在嘗試驗證文本框。 基本上,如果用戶輸入的數字少於2或為非數字,那么如何顯示錯誤。 這是我要遵循的教程

我下面有我的代碼。

創建視圖:

<%= 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方法'AddModelError'的重載不占用1個CharitySite

您將錯誤錯誤地添加到模型狀態。 您可以在MSDN上閱讀有關ModelStateDictionary的更多信息。

AddModelError需要2個參數,因此您需要:

ModelState.AddModelError("Amount", "Greater Than 2 Please.");

話雖如此,您可以使用屬性來驗證模型屬性,因此您不必手動編寫所有代碼。 下面是使用Range屬性的示例。 RegularExpression屬性也可以使用。 這是MSDN文章,其中包含有關不同類型的屬性的信息。

public class Charity
{
    public int ID { get; set; }
    public string DisplayName { get; set; }
    public DateTime Date { get; set; }

    [Range(2, Int32.MaxValue, ErrorMessage = "The value must be greater than 2")]
    public Double Amount { get; set; }
    public Double TaxBonus { get; set; }
    public String Comment { get; set; }
}

另外,您要遵循的教程是針對MVC 1&2的。 除非您必須使用/學習。 我會推薦教程MVC 5以下這里

更改此行:

ModelState.AddModelError("Amount, Greater than 2 please");

至:

ModelState.AddModelError("Amount ", "Amount, Greater than 2 please");

第一個參數是正在驗證的模型的成員; 它可以是一個空字符串,僅表示與字段無關的錯誤。 通過指定Amount字段,如果您使用所有客戶端驗證塊,則在內部使用Amount字段突出顯示錯誤字段(控件應在其中添加了input-validation-error CSS類)。

ModelState.AddModelError接受2個參數,而不是1個。鏈接到MSDN ModelStateDictionary.AddModelError Method

ModelState.AddModelError("Amount", "Greater than 2 please");
if (productToCreate.Amount < 2)
    ModelState.AddModelError("Amount", "Greater than 2 please");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM