2012-11-16 64 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);