2011-08-09 42 views
0

我有以下控制器。如果發生錯誤但表單數據丟失,則返回視圖。 有沒有人有一個想法,我怎麼可以返回與視圖的表單數據?使用表單數據返回查看

[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Register(FormCollection collection) 
    { 
     string usrname = collection["UserName"]; 
     string email = collection["Email"]; 
     string password = collection["Password"]; 
     string serial = collection["Serial"]; 
     ViewData["PasswordLength"] = MembershipService.MinPasswordLength; 
     // In a real app, actually register the user now 
     if (ValidateRegistration(usrname, email, password, password)) 
     { 
      // Attempt to register the user 
      MembershipCreateStatus createStatus = MembershipService.CreateUser(usrname, password, email, serial); 

      if (createStatus == MembershipCreateStatus.Success) 
      { 
       //TODO userinformation 

       datacontext.SaveChanges(); 
       FormsAuth.SignIn(collection["UserName"], false /* createPersistentCookie */); 
       return RedirectToAction("Index", "Home"); 
      } 
      else 
      { 
       ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus)); 

       //I would like to return the view with the form data 

       return View(); 
      } 
     } 

回答

2

你絕對應該使用視圖模型,強類型的意見,並擺脫任何FormCollection和魔術字符串,像這樣:

public class RegisterUserViewModel 
{ 
    public string UserName { get; set; } 
    public string Email { get; set; } 
    public string Password { get; set; } 
    public string Serial { get; set; } 
    public int PasswordLength { get; set; } 
} 

然後:

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Register(RegisterUserViewModel model) 
{ 
    model.PasswordLength = MembershipService.MinPasswordLength; 
    // In a real app, actually register the user now 
    if (ValidateRegistration(model.UserName, model.Email, model.Password, model.Password)) 
    { 
     // Attempt to register the user 
     MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.Serial); 
     if (createStatus == MembershipCreateStatus.Success) 
     { 
      //TODO userinformation 
      datacontext.SaveChanges(); 
      FormsAuth.SignIn(model.UserName, false /* createPersistentCookie */); 
      return RedirectToAction("Index", "Home"); 
     } 
     else 
     { 
      ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus)); 
      return View(model); 
     } 
    } 

    ... 
} 

在Visual Studio的默認ASP。 NET MVC 3應用程序嚮導創建了一個如何在AccountController中執行此操作的示例。

0

首先,我會建議使用PRG pattern(不從我們的POST操作返回查看)

您將需要存儲的ModelState在臨時數據,但你可以用行動過濾器屬性很容易做到這一點 - 見blog post中的第13點。