全,
我有两个视图模型(两个不同的页面),它们都包括并需要一个模型类(NewClub),它具有必需的属性,但是在第二个视图之前不需要这些必需的属性。基本上,视图#1更新/插入模型类NewClub中的一些属性,而视图#2在模型类NewClub中插入/更新其他属性。
我试图忽略视图#1中不需要的所需属性,在视图#1控制器中,如下所示:
ModelState.Remove("NewClub.ClubCounselorContact");
ModelState.Remove("NewClub.ClubCounselorEmail");
ModelState.Remove("NewClub.ClubCounselorPhone");这使模型状态验证通过,但当我保存时:
model.NewClub.NewClubType = model.ClubTypeSelected;
db.NewClubs.Add(model.NewClub);
db.Entry(model.NewClub).State = EntityState.Modified;
try
{
var dbResult = db.SaveChanges() > 0;
}我得到:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.有办法绕过这件事吗?
谢谢
示例:
public class NewClub
{
public string ClubCounselorMasterCustomerId { get; set; }
//Used only on view page #2
[Display(Name = "Club counselor")]
[Required(ErrorMessage = "Club counselor name")]
public string ClubCounselorContact { get; set; }
//Used only on view page #2
[Display(Name = "Club counselor email")]
[Required(ErrorMessage = "Club counselor email")]
public string ClubCounselorEmail { get; set; }
//Used only on view page #2
[Display(Name = "Club counselor phone")]
[Required(ErrorMessage = "Club counselor phone")]
public string ClubCounselorPhone { get; set; }
[...]
}
//View Model #1
public class LetsGetStartedViewModel
{
public NewClub NewClub { get; set; }
public bool HasExistingBuildingClubs { get; set; }
[...]
}
//View Model #2
public class FormANewClubTeamViewModel
{
public NewClub NewClub { get; set; }
public List<NewClubSponsor> Sponsors { get; set; }
[...]
}发布于 2014-01-02 14:34:18
这里真正的问题是,您没有充分利用视图模型的功能。这就是为什么在视图中使用域模型不是一个好主意的确切原因,因为如果视图有不同的验证要求,那么您就没有足够的灵活性来处理它。
因此,我建议的不是在视图模型中直接使用NewClub,而是在视图模型中添加属性来表示NewClub所需的属性。这样,您就可以为每个单独的视图使用数据注释来修饰这些属性,这意味着验证规则可能会改变。然后,将视图模型中的属性映射回域模型。
例如:
public class LetsGetStartedViewModel
{
[Required]
public string ClubCounselorContact { get; set; }
}
public class FormANewClubTeamViewModel
{
public string ClubCounselorContact { get; set; }
}那么您的控制器可能如下所示:
[HttpPost]
public ActionResult SomeAction(LetsGetStartedViewModel model)
{
if (ModelState.IsValid)
{
// map properties onto a NewClub, then add it to db or whatever
NewClub newClub = new NewClub
{
ClubCounselorContact = model.ClubCounselorContact
};
// add to database
return RedirectToAction("Success");
}
return View(model);
}发布于 2014-01-02 14:34:00
你写:
必需属性,但在第二个视图之前不需要这些必需的属性
这意味着您的模型是不同的,因此每个视图都应该有自己的模型;每个视图都有正确的Required标记。
是的,它需要复制/粘贴,但是(1)这是迄今为止最简单的解决方案,(2)它在概念上也是正确的:对不同视图的不同需求意味着不同的模型。
https://stackoverflow.com/questions/20885174
复制相似问题