2013-02-11 47 views
1

我正在使用ASP MVC 4.0,并想了解自定义验证的基础知识。在这种特殊情况下,模型与控制器或视图完全没有强类型,所以我需要不同的东西。简单的MVC错误流程

我想要做的是接受一个新的用户名注册我的服务,查看数据库,并重新呈现原始表单与消息,如果该用户名被采取。

这是我的输入形式:

@{ 
    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(); 
     } 

如果成功是假的,我只是想重新目前的形式一条消息表明如此。我错过了这个错误流的基础知识。你能帮忙吗?提前致谢。

+1

我想你完全错过了关于MVC的观点。你应该使用模型来实现这样的事情。那么,这些模型可以对它们进行验证,以便更好地将其发送回页面。 – IronMan84 2013-02-11 20:28:34

回答

1

可以添加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); 
    } 
} 

...甚至写自己的验证,只是装饰你的模型属性,无需控制器检查成功。