How can I reuse a DropDownList in several views with .NET MVC

后端 未结 13 1102
感动是毒
感动是毒 2020-12-13 15:53

Several views from my project have the same dropdownlist...

So, in the ViewModel from that view I have :

public IEnumerable Fo         


        
13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 16:14

    I'd say that's fine to be honest, as it's only a repeat of a few lines of code. If it's really bothering you though, you could have all your controllers inherit from a BaseController (if they don't already) and store a method in there to get them all, something like:

    public IEnumerable GetFoos()
    {
        return fooRepository.GetAll().ToSelectList(x => x.Id, x => x.Name);
    }
    

    Then in your controllers you could do:

    var MyVM = new MyVM() {
        FooDdl = GetFoos()
    }
    

提交回复
热议问题