需要具有Bind属性的MVC操作方法的指南

Tho*_*mas 50 c# asp.net-mvc asp.net-mvc-3

我正在通过一个动作方法代码,我看到在那里使用了一个属性,但我真的不明白使用.这是代码

public ActionResult User([Bind(Include = "Username,FullName,Email")]User user)
{
   if (!ModelState.IsValid()) return View(user);

   try
   {
     user.save()
     // return the view again or redirect the user to another page
   }
   catch(Exception e)
   {
     ViewData["Message"] = e.Message;
     return View(user)
   }
}

([Bind(Include = "Username,FullName,Email")]User user)
Run Code Online (Sandbox Code Playgroud)

我只是不明白上面的行Bind include等

所以请帮助我理解这种使用的属性以及人们在mvc中编写这种代码的时候.如果有人让我理解他们将使用它的示例小代码,那将是非常好的帮助Bind attribute.

更新: 假设我有表单,用户只能输入FirstName,LastName和Gender,然后我的操作方法看起来像

public ActionResult Edit(string FirstName,string LastName,string Gender)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我觉得这会奏效.那么为什么我应该使用绑定属性,因为我的上述操作方法将正常工作.

hai*_*770 87

Bindattribute允许您"微调"某个参数Type的模型绑定过程,而无需注册ModelBinder特定于Type 的自定义.

例如,假设您的Action期望Person定义如下的参数:

public class Person
{
    public Person(string firstName, string lastName, Gender gender)
    {
        this.FirstName = firstName;
        this.LastName = lastName;

        if (gender == Gender.Male)
            this.FullName = "Mr. " + this.FirstName + " " + this.LastName;
        else
            this.FullName = "Mrs. " + this.FirstName + " " + this.LastName;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Gender Gender { get; set; }

    // 'FullName' is a computed column:
    public string FullName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

行动:

public ActionResult Edit(Person person)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在,如果有人发布以下JSON:

{
    "FirstName":"John",
    "LastName":"Smith",
    "Gender":"Male",
    "FullName":"Mrs. John Smith"
}
Run Code Online (Sandbox Code Playgroud)

你的行动现在会person出错FullName('太太'代替'先生').

要避免此类行为,您可以使用该Bind属性并FullName从绑定过程中明确排除该属性('Black-list'):

public ActionResult Edit([Bind(Exclude="FullName")] Person person)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用Include忽略('Black-list')所有属性并仅包含('White-list')指定的属性:

public ActionResult Edit([Bind(Include="FirstName,LastName,Gender")] Person person)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

有关MSDN的更多信息.


gre*_*g84 16

执行此操作时,MVC模型绑定器将使用请求参数来填充user参数的属性,您可能已经知道.但是,该Bind属性告诉模型绑定器填充指定名称的属性.

因此,在这种情况下,只有Username,FullNameEmail属性将被填充.所有其他人都将被忽略.

有关详细信息,请参见此处:http://ittecture.wordpress.com/2009/05/01/tip-of-the-day-199-asp-net-mvc-defining-model-binding-explicitly/