0

I have a view model

public class ViewModel
{
      public string Text { get; set; } 
      public string Name { get; set; } 
}

The submited form provides only the Text value. I'd like to set the the Name property in my custom model binder.

So I derived my custom model binder from the DefaultModelBinder class and overrided the BindModel method.

The problem is that the BindModel method is called only for the incomning properties.

My question is how can I set the Name value in my cystom model binder ?

1 Answer 1

0

If you do not have an incoming value for Name, then you are not doing (custom) model binding. Instead, you want to supply some data in your model object before the action executes, right ? If so, use ActionFilter for it, override OnActionExecuting() and supply the data you need into action parameters.

public class SupplyNameAttribute : FilterAttribute, IActionFilter
{
 public void OnActionExecuting(ActionExecutingContext filterContext)
 {
    if (filterContext.ActionParameters != null)
     {
         foreach (KeyValuePair<string, object> parameter in filterContext.ActionParameters)
         {
             if (parameter.Key == "Name") parameter.Value == "Hey";
         }
     }        
 }

}

EDIT :

You can also use custom ValueProvider for default model binding, see

http://mgolchin.net/posts/19/dive-deep-into-mvc-ivalueprovider

Sign up to request clarification or add additional context in comments.

4 Comments

But the actionparametr is an object and this Name property can be used in many viewmodels.
well, then you have to use reflecton - first test the object with "is" operator for "supported" type, then find Name property with reflection and set value
I don't understand how a custom ValueProvider can help ? Could you please explain it little bit more ?
The custom valueprovider was exactly the right thing for this situation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.