如何使用Controller.TryUpdateModel <tmodel> Method(TModel,String,String [],String [])绑定模型对象以排除某些属性?</tmodel>

时间:2010-08-13 12:19:29

标签: asp.net-mvc model-binding

假设我有以下模型

public class MyClass
{
  public type1 Property1 { get; set; }
  public type1 Property2 { get; set; }
  public type1 Property3 { get; set; }
  public type1 Property4 { get; set; }
  public type1 Property5 { get; set; }  
}
例如,我想只绑定前3个属性。我怎么能这样做使用Overload for TryUpdateModel()这样的

TryUpdateModel<TModel> Method (TModel, String, String[], String[])

修改

我不会在动作方法上更新我的模型,而是像这样使用 OnActionExecuting 过滤器:

 public class RegistrationController : Controller
{

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var serialized = Request.Form["formViewModel"];
        if (serialized != null)
        {
            formViewModel = (FormViewModel)new MvcSerializer().Deserialize(serialized);
            TryUpdateModel(formViewModel);
        }
        else
            formViewModel = (FormViewModel)TempData["formViewModel"] ?? new FormViewModel();
    }
  //All the action methods are here
 }

因此,我想根据视图发回的操作排除部分属性。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您可以使用默认的MVC模型绑定,但只需在您的类上面包含以下内容:

[Bind(Exclude = "Property1,Property2")]
public class MyClass
{
  public type1 Property1 { get; set; }
  public type1 Property2 { get; set; }
  public type1 Property3 { get; set; }
  public type1 Property4 { get; set; }
  public type1 Property5 { get; set; }  
}

顺便说一句,你也可以使用:

[Bind(Include = "Property3,Property4,Property5")]
public class MyClass
{
  public type1 Property1 { get; set; }
  public type1 Property2 { get; set; }
  public type1 Property3 { get; set; }
  public type1 Property4 { get; set; }
  public type1 Property5 { get; set; }  
}

回答你的问题...............

您可以将排除指令放在ActionResult方法中,如此...

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create( [Bind(Exclude="Property1,Property2")] MyClass myClass)
{ 
     your code....
}