1

Say I have a controller method, that accepts just a string:

[HttpPost]
public ActionResult DoSomething(string emailAddress)
{
    //
}

How could I validate that emailAddress isn't null...? Obviously I can't use DataAnnotations, as I don't have a model?

3
  • the naive question is why not just use a model. You might have one parameter now, but adding another in the future would be easier and less likely to break the method signature. Just my 2 cents. Commented Jul 22, 2013 at 13:37
  • In an agile way of working, the additional complexity of creating a model would be done as and when needed. With one property, it's not needed Commented Jul 22, 2013 at 13:42
  • I would say the added noise in the controller action (from the solutions) would warrant that tiny additional complexity, but that's just my personal preference. Rules are made to be broken when the solution makes more sense than the constraint. Commented Jul 22, 2013 at 13:45

2 Answers 2

2

How about just

[HttpPost]
public ActionResult DoSomething(string emailAddress)
{
    if (string.IsNullOrWhiteSpace(emailAddress))
    {
        ModelState.AddModelError("emailAddress", "Please enter an email");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

This should work:

[HttpPost]
public ActionResult DoSomething(string emailAddress)
{
    if (string.IsNullOrEmpty(emailAddress))
        ModelState.AddModelError("emailAddress", "Email address is empty");

    if (ModelState.IsValid)
    {
        // Do something
    }

    return View();
}

To show the error, include a ValidationSummary in your view.

1 Comment

[ValidateInput(False)] [HttpPost] public ActionResult DoSomething(string emailAddress) .. this may help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.