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

別のアクションで給与が必要な場合は、このビューに固有の別のビュー モデルを記述します。ビュー モデル間でいくつかのプロパティを繰り返しても心配はいりません。それがまさに彼らの目的です。明らかに、リポジトリはビューモデルではなくモデルで機能します。そのため、これら 2 つのタイプをマッピングする必要があります。この目的にはAutoMapperを使用することをお勧めします。

それが私の見解です。特定のビューのニーズに合わせて特別に調整されたビュー モデルを常に記述します。これらの包含、除外を避けるようにしてください。そうしないと、ある日、誰かが機密性の高いプロパティを追加しようとして、それを除外リストに追加するのを忘れる可能性があります。そして、インクルードを使用したとしても、それはまだ醜いです.

于 2010-12-18T16:35:14.327 に答える