c# - Custom Model Binder does not fire -


i have registered custom model binder mylist in global.asax. model binder not fire nested properties, simple types works fine. in example below, fires index() not not fire index2()

global.asax

protected void application_start() {     arearegistration.registerallareas();      modelbinders.binders.add(typeof(mylist), new mylistbinder());      webapiconfig.register(globalconfiguration.configuration);     filterconfig.registerglobalfilters(globalfilters.filters);     routeconfig.registerroutes(routetable.routes); } 

code:

public class mylistbinder : imodelbinder {     public object bindmodel(controllercontext controllercontext, modelbindingcontext bindingcontext)     {         return new mylist();     } }  public class mylist {     public list<int> items { get; set; } }  public class mylistwrapper {     public mylist listitems { get; set; } }  public class testcontroller : controller {     public actionresult index(mylist list)  // modelbinder fires :-)     {                     return view();     }      public actionresult index2(mylistwrapper wrapper) // modelbinder not fire! :-(     {         return view();     } } 

model binders used allow actions accept complex object types parameters. these complex types should generated via post requests, example, submitting form. if have highly complex object cannot binded default model binder (or wouldn't effective), can use custom model binders.

to answer question: if don't add custom model binder mylistwrapper class too, bindmodel(of mylistbinder)won't called in request, how asp.net mvc works. however, if modify code adding post action mylistwrapper parameter, can see bindmodel method called properly.

[httpget] public actionresult index2()  // modelbinder doesn't fire {     return view(); }  [httppost] public actionresult index2(mylistwrapper wrapper) // modelbinder fires {     return view(); } 

and index2 view

@model fun.web.mylistwrapper  @using (html.beginform()) {     @html.hiddenfor(m => m.listitems)     <input type="submit" value="submit" /> } 

if you'd "control" action parameters in request, should use action filters.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -