0

我正在做一个登记表。在提交时,我检查电子邮件地址是否已在数据库中注册。如果是这种情况,我会使用一个空的电子邮件地址再次重定向到注册表单。

表单已填写,但电子邮件地址仍然是用户第一次填写的电子邮件地址。这怎么可能?这是我的一些代码

剃刀页面

@model LibModels.User
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend></legend>

        <div class="row">
            @Html.LabelFor(model => model.userEmail)
            @Html.EditorFor(model => model.userEmail)
            @Html.ValidationMessageFor(model => model.userEmail)
        </div>    <p>
            <input id="knop" type="submit" value="Create" />
        </p>
    </fieldset>
}

控制器

[HttpPost]


public ActionResult Register(User viewModel)
    {
        User usr = Adapter.UserRepository.Single(u => u.userEmail.Equals(viewModel.userEmail));
        if (usr == null)
        {
            viewModel.userCreatedDate = DateTime.Now;
            Adapter.UserRepository.Insert(viewModel);
            Adapter.Save();
        }
        else
        {
            viewModel.userEmail = "";
            return View(viewModel);
        }
        return RedirectToAction("Index");
    }

在验证该电子邮件地址已存在于数据库中时发出警告也很好,最好的方法是什么?

4

1 回答 1

1

I think what you're looking for is

ModelState.AddModelError("userEmail", "Email already exists");

However, I'd suggest looking into creating a custom action filter to do the validation for you. It's a lot cleaner & easy to test.

Here's a tutorial.

于 2013-04-20T20:43:26.730 回答