2016-03-02 56 views
1

我是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

+0

在MVC中,您不驗證文本框,而是驗證模型。文本框與模型屬性相關聯,如果模型的這些屬性不驗證,則顯示與該屬性的文本框相關聯的錯誤。 –

+1

你爲什麼從2009年開始接受教程?如果你想學習asp.net MVC,請學習最新版本。 – ataravati

回答

4

您錯誤地將這個錯誤給ModelState中。你可以閱讀更多關於ModelStateDictionary上MSDN

AddModelError需要兩個參數,所以你會想:

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 here的教程。

+0

感謝您的答案和教程! ,我嘗試了你的第二種方法,但在「Range」和「ErrorMessage」下面出現了一條扁平的紅線,說「找不到類型或名稱空間名稱」(缺少using指令或程序集引用?如何解決這個問題? – John

+0

@john如果你使用的是visual studio,你應該能夠在你的光標處於水平狀態時「ctrl +。」,並獲得包含的使用清單。如果沒有,你應該只需要:'使用系統; using System.ComponentModel.DataAnnotations;' – drneel

+0

Top lad!非常感謝你。 – John

1

改變這一行:

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

到:

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

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

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