How to bind URL parameters to model properties with different names

后端 未结 5 1183
你的背包
你的背包 2020-12-16 01:18

Okay, lets say I have a URL like so, which is mapped via HTTP verb GET to the controller action I have below:

GET /foo/bar?sort=asc&r=true
<         


        
5条回答
  •  不知归路
    2020-12-16 01:21

    The model binder matches the parameters it gets from the view to the model you have in the action by the Names, so if they won't match the binding will not work.

    options you got:

    1. Match the inputs names to the model properties names... but You said you can't do this, (for some unknown reason).
    2. Write custom Model Binder. *
    3. Use The Bind attribute with prefix - though it'll still force you to have input names close to the model properties names.

    so basically, You can't do exactly what you want.


    Update:

    You wrote in a comment that the properties CAN match the parameters names, so instead of write custom attributes that maybe will succeeded to do the binding, just write a ViewModel (The VM fromMVC...) to adjust the url parameters names.

    Writing custom model binder is not recommended by the MVC team:

    In general, we recommend folks don’t write custom model binders because they’re difficult to get right and they’re rarely needed
    from here

提交回复
热议问题