使用接口排除模型结合上的属性
-
10-10-2019 - |
题
这是我在这里举起的一个例子: http://aspalliance.com/1776_aspnet_mvc_beta_released.5
public ActionResult Save(int id)
{
Person person = GetPersonFromDatabase(id);
try
{
UpdateMode<IPersonFormBindable>(person)
SavePersonToDatabase(person);
return RedirectToAction("Browse");
}
catch
{
return View(person)
}
}
interface IPersonFormBindable
{
string Name {get; set;}
int Age {get; set;}
string Email {get; set;}
}
public class Person : IBindable
{
public string Name {get; set;}
public int Age {get; set;}
public string Email {get; set;}
public Decimal? Salary {get; set;}
}
这不会将值映射到财产工资,而是执行其验证属性,而执行标准时不会预期 bind(排除=“薪金”)
[Bind(Exclude="Salary")]
public class Person
{
public string Name {get; set;}
public int Age {get; set;}
public stiring Email {get; set;}
public Decimal? Salary {get; set;}
}
我将如何实施 bind(dubl =“属性”) 使用此接口模式?
解决方案
这是我建议您的建议:使用视图模型,丢弃这些接口,不要用太多代码混乱控制器。因此,您不需要在此特定行动中绑定薪水:太好了,对此视图使用专门量身定制的视图模型:
public class PersonViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
和您的控制器操作:
public ActionResult Save(PersonViewModel person)
{
_repository.SavePersonToDatabase(person);
return RedirectToAction("Browse");
// Notice how I've explicitly dropped the try/catch,
// you weren't doing anything meaningful with the exception anyways.
// I would simply leave the exception propagate. If there's
// a problem with the database it would be better to redirect
// the user to a 500.htm page telling him that something went wrong.
}
如果在另一个行动中需要薪水,请编写特定于此视图的另一个视图模型。如果您在视图模型之间重复一些属性,请不要担心。这正是他们的意思。显然,您的存储库将使用模型而不是查看模型。因此,您需要在这两种类型之间进行映射。我建议您使用 汽车应用程序 以此目的。
这是我的观点:始终编写专门针对给定视图的需求量身定制的视图模型。尽量避免使用这些内容,排除或有一天会咬您,有人将添加一些敏感的属性,并且会忘记将其添加到排除列表中。即使您使用的是包含它仍然很丑。
不隶属于 StackOverflow