1

假设我有一个控制器方法,它只接受一个字符串:

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

我怎么能验证它emailAddress不为空......?显然我不能使用 DataAnnotations,因为我没有模型?

4

2 回答 2

2

刚刚怎么样

[HttpPost]
public ActionResult DoSomething(string emailAddress)
{
    if (string.IsNullOrWhiteSpace(emailAddress))
    {
        ModelState.AddModelError("emailAddress", "Please enter an email");
    }
}
于 2013-07-22T11:40:42.203 回答
1

这应该有效:

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

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

    return View();
}

要显示错误,请在您的视图中包含 ValidationSummary。

于 2013-07-22T11:42:11.620 回答