1

I am new to ASP.NET MVC and am trying to validate a text-box. Basically, if user inputs less than 2 or a non number how can I get the error to display. Here's the tutorial I am trying to follow.

I have my code below.

Create View:

<%= Html.ValidationSummary()%>
<%= using (HtmlBeginForm()){%>
<div class="half-col">
    <label for="Amount">Amount:</label>
    <%= Html.TextBox("Amount")%>
    <%= Html.ValidationMessage("Amount", "*")%>
</div>

Create Controller:

[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 
}

Model:

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; }
}

Error:

CS1501 No overload for method 'AddModelError' takes 1 CharitySite

2
  • In MVC, you do not validate a textbox, you validate a model. Textboxes are associated with model properties, and if those properties of the model do not validate, then the error is displayed associated with the textbox for that property. Commented Mar 2, 2016 at 19:41
  • 1
    Why are you following a tutorial from 2009? If you want to learn asp.net MVC, learn the latest version. Commented Mar 2, 2016 at 19:52

4 Answers 4

4

You are adding the error to your modelstate incorrectly. You can read more about the ModelStateDictionary on the MSDN

AddModelError takes 2 parameters, so you would want:

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

Having said that, you can use attributes to validate your model properties so you don't have to write all of that code by hand. Below is an example using the Range attribute. The RegularExpression attribute could also work. Here is an MSDN article containing information about the different types of attributes.

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; }
}

Also as a side note, the tutorial you are following is for MVC 1&2. Unless you HAVE to use / learn that. I would recommend following the tutorial for MVC 5 here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer and tutorials! , I tried your second approach but a squigly red line appears under "Range" and "ErrorMessage" saying "The type or namespace name " " could not be found.(are you missing a using directive or assembly reference?)" , any idea how this can be resolved?
@john If you're using visual studio you should be able to ctrl + . when your cursor is on the squiggly and get a list of the usings to include. If not, you should just need: using System; using System.ComponentModel.DataAnnotations;
1

Change this line:

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

to:

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

The first parameter is the member of the model being validated; it can be an empty string just to indicate an error not associated to a field. By specifying the Amount field, internally it uses that to highlight the erroring field (the control should have input-validation-error CSS class added to it) if you are using all of the client-side validation pieces.

Comments

1

ModelState.AddModelError takes 2 arguments, not 1. Link to MSDN ModelStateDictionary.AddModelError Method.

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.