[英]Partial View validation with composite view model
我有两种形式的屏幕。 一个允许登录到站点,另一个允许登录到ftp。
Login视图使用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(“ Logon”,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无效时返回什么。 如何返回带有验证摘要错误的页面? 上面显示的代码仅返回部分视图表单(不在主表单内部),没有验证。 我究竟做错了什么? 我从这篇文章开始,但没有显示足够的代码来帮助我。
任何帮助,将不胜感激。 谢谢。
我的代码有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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.