3

这是我在这里举的一个例子: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;}
}

这不会将值映射到属性 Salary 但将执行其验证属性,这在您执行标准[Bind(Exclude="Salary")]时不会出现

[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(Exclude="Property")] ?

4

1 回答 1

2

以下是我向您推荐的内容:使用视图模型,并放弃这些接口,不要用太多代码弄乱您的控制器。因此,您不需要在此特定操作中绑定薪水:太好了,为此视图使用专门定制的视图模型:

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.
}

如果在另一个操作中您需要薪水,那么编写另一个特定于该视图的视图模型。如果您在视图模型之间重复某些属性,请不要担心。这正是它们的目的。显然,您的存储库将使用模型而不是视图模型。所以你需要在这两种类型之间进行映射。为此,我建议您使用AutoMapper 。

这就是我的观点:始终编写专门针对给定视图需求定制的视图模型。尽量避免那些包含、排除或有一天它会咬你,有人会添加一些敏感属性,并且会忘记将其添加到排除列表中。即使你使用了 Include 它仍然很丑。

于 2010-12-18T16:35:14.327 回答