views:

29

answers:

1

Hello,

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"] ?? 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

A: 

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....
}
mikerennick
@mikerennick: it looks like you are applying the include/exclude at the class level. Can you use TryUpdateModel(model, //whatever to exclude)?
Richard77
I edited my answer in response to this question.
mikerennick
@mikerennick: I'll tell you why I want you to use TryUpdateModel. See the edit on my post.
Richard77