2012-11-16 38 views
0

我有兩種形式的屏幕。一個允許登錄到該站點,另一個允許登錄到一個ftp。使用複合視圖模型進行部分視圖驗證

登錄視圖用WelcomeScreenViewModel(組合模型)強烈鍵入。 每個表單都是強類型的局部視圖。

這裏是類定義。

public class LogOnViewModel 
    { 
     [LocalizedDisplayNameAttribute("username", typeof(MyLabels.labels))] 
     [Required] 
     public string UserName { get; set; } 
     [LocalizedDisplayNameAttribute("password", typeof(MyLabels.labels))] 
     [Required] 
     public string Password { get; set; } 
    } 

    public class FTPViewModel 
    { 
     [LocalizedDisplayNameAttribute("username", typeof(MyLabels.labels))] 
     [Required] 
     public string UserName { get; set; } 
     [LocalizedDisplayNameAttribute("password", typeof(MyLabels.labels))] 
     [Required] 
     public string Password { get; set; } 
    } 

    public class WelcomeScreenViewModel 
    { 
     public LogOnViewModel LogOnModel { get; set; } 
     public FTPViewModel FTPModel { get; set; } 
    } 

我的主頁繼承WelcomeScreenViewModel和我使我的部分景色是這樣的:

Html.RenderPartial( 「登錄」,Model.LogOnModel);

Html.RenderPartial(「FTP」,Model.FTPModel);

我的控制器代碼:

// To display blank login on load of page 
public ActionResult Login(string language) 
     { 
      WelcomeScreenViewModel combined = new WelcomeScreenViewModel(); 
      combined.FTPModel = new FTPViewModel(); 
      combined.LogOnModel = new LogOnViewModel(); 
      return View(combined); 
     } 

// Called when clicking submit on first form 
[AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult Logon(string language, LogOnViewModel logon) 
     { 
      WelcomeScreenViewModel combined = new WelcomeScreenViewModel(); 
      combined.FTPModel = new FTPViewModel(); 
      combined.LogOnModel = logon; 

      if (!ModelState.IsValid) 
      { 
       ViewData["result"] = "Invalid login info/Informations de connexion incorrectes"; 

       // This is the part I can't figure out. How do I return page with validation summary errors 
       return View(logon); 
      } 
      else 
      { 
       ... 
      }    
     } 

到目前爲止,我的問題是什麼,返回時,我的ModelState是無效的。如何返回包含驗證摘要錯誤的頁面?上面顯示的代碼只是返回部分視圖表單(不在主表單中)而不進行驗證。我究竟做錯了什麼?我開始使用this post,但它沒有顯示足夠的代碼來幫助我。

任何幫助,將不勝感激。謝謝。

回答

1

我的代碼有2個問題。

1)兩個子模型必須爲每個字段有不同的名稱。

public class LogOnViewModel 
    { 
     [LocalizedDisplayNameAttribute("username", typeof(MyLabels.labels))] 
     [Required] 
     public string UserName { get; set; } 
     [LocalizedDisplayNameAttribute("password", typeof(MyLabels.labels))] 
     [Required] 
     public string Password { get; set; } 
    } 

    public class FTPViewModel 
    { 
     [LocalizedDisplayNameAttribute("username", typeof(MyLabels.labels))] 
     [Required] 
     public string ftpUserName { get; set; } 
     [LocalizedDisplayNameAttribute("password", typeof(MyLabels.labels))] 
     [Required] 
     public string ftpPassword { get; set; } 
    } 

2)這是代碼使用返回的驗證和值:

return View("~/Views/Login/Login.aspx",combined);