简体   繁体   中英

Custom Model Binder

I'd like to create a custom model binder.

Let's say there're 20 properties. I need manualy bind only five of them. I'd like to bind the other 15 properties automatic like the default binder does.

Is this somehow possible ?

Sure, the very least thing you can do is inherit DefaultModelBinder , override the BindModel(...) method and use base.BindModel(...) for whatever you want. After that just provide your own binding logic for anything else.

I had such problem few days ago and I have solved it by filling the default properties inside the constructor . In this way I just pass the model without any problem even if I don't have an "Author" field:

public class Post
{
    private string title;
    private string author;
    private string content;

    public string Title
    {
        get { return title; }
        set { title = value; }
    }

    public string Author
    {
        get { return author; }
        set { author = value; }
    }

    public string Content
    {
        get { return content; }
        set { content = value; }
    }

    public Post()
    {
        this.author = "Davis";
    }
}

这里MVC中的模型绑定器是创建自定义模型绑定器以及模型绑定器在 asp.net MVC 中究竟是如何工作的一个很好的例子。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM