开发者

How can I bind a model object using Controller.TryUpdateModel<TModel> Method (TModel, String, String[], String[]) to exclude some properties?

Let's say I've the following model

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

I would, for instance, like to bind only the first 3 properties. How can I do so Using one of the Overload for TryUpdateModel() like this

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

EDIT

I don't update my model on the action method but rather using an OnActionExecuting filter like this:

 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"] ??开发者_C百科 new FormViewModel();
    }
  //All the action methods are here
 }

So, I'd like to exclude some of the properties depending on which action the view is posting back.

Thanks for helping


You can use the default MVC model binding, but just include the following above your class:

[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; }  
}

incidentally, you could also use:

[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; }  
}

ANSWER TO YOUR QUESTION...............

You can place the exclude directive in the ActionResult method like so...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜