简单的MVC错误流

本文关键字:错误 MVC 简单 | 更新日期: 2023-09-27 17:58:39

我使用的是ASP MVC 4.0,希望了解自定义验证的基础知识。在这种特殊的情况下,模型与控制器或视图根本不是强类型的,所以我需要一些不同的东西。

我想做的是在注册我的服务时接受一个新用户名,查看数据库,如果使用了该用户名,则在原始表单中重新显示一条消息。

这是我的输入表格:

@{
    ViewBag.Title = "Index";
}
<h2>New account</h2>
<form action= "@Url.Action("submitNew", "AccountNew")" method="post">
    <table style="width: 100%;">
        <tr>
            <td>Email:</td>
            <td>&nbsp;</td>
            <td><input id="email" name="email" type="text" /></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td>&nbsp;</td>
            <td><input id="password" name="password" type="password" /></td>
        </tr>
        <tr>
            <td>Confirm Password:</td>
            <td>&nbsp;</td>
            <td><input id="passwordConfirm" name="passwordConfirm" type="password" /></td>
        </tr>
        <tr>
            <td></td>
            <td>&nbsp;</td>
            <td><input id="Submit1" type="submit" value="submit" /></td>
        </tr>
    </table>
</form>

这是我提交时的控制器方法:

    public ActionResult submitNew()
        {
            SomeService service = (SomeService)Session["SomeService"];
            string username = Request["email"];
            string password = Request["password"];
            bool success = service.guestRegistration(username, password);
            return View();
        }

如果成功是错误的,我只想在表单中重新显示一条消息,表明这一点。我错过了这个错误流的基本内容。你能帮忙吗?提前谢谢。

简单的MVC错误流

可以添加ViewBag项目

bool success = service.guestRegistration(username, password);
if (!success)
{
  ViewBag.Error = "Name taken..."
}
return View();

但是您应该创建一个视图模型。。。

public class ViewModel
{
  public string UserName {get; set;}
  //...other properties
}

强烈键入您的视图并使用内置的html助手。。。

@model ViewModel
//...
@using BeginForm("SubmitNew", "AccountNew", FormMethod.Post)()
{
  //...
  <div>@Html.LabelFor(m => m.Username)</div>
  <div>@Html.TextBoxFor(m => m.Username)</div>
  <div>@Html.ValidationMessageFor(m => m.Username)</div>
}

并利用控制器中的ModelState

[HttpPost]
 public ActionResult SubmitNew(ViewModel viewModel)
 {
     if(ModelState.IsValid)
     {
       SomeService service = (SomeService)Session["SomeService"];
       bool success = service.guestRegistration(viewModel.username, viewModel.password);
       if (success)
       {
          return RedirectToAction("Index");
       }
       ModelState.AddModelError("", "Name taken...")"
       return View(viewModel);
     }
 }

或者甚至编写自己的验证器,只需装饰模型属性,就不需要在控制器中检查成功与否。