2013-02-11 48 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); 
    } 
} 

...甚至寫自己的驗證,只是裝飾你的模型屬性,無需控制器檢查成功。