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

后端 未结 13 1081
感动是毒
感动是毒 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:29

    What about a Prepare method in a BaseController?

    public class BaseController : Controller
    {
        /// 
        /// Prepares a new MyVM by filling the common properties.
        /// 
        /// A MyVM.
        protected MyVM PrepareViewModel()
        {
            return new MyVM()
            {
                FooDll = GetFooSelectList();
            }
        }
    
        /// 
        /// Prepares the specified MyVM by filling the common properties.
        /// 
        /// The MyVM.
        /// A MyVM.
        protected MyVM PrepareViewModel(MyVM myVm)
        {
            myVm.FooDll = GetFooSelectList();
            return myVm;
        }
    
        /// 
        /// Fetches the foos from the database and creates a SelectList.
        /// 
        /// A collection of SelectListItems.
        private IEnumerable GetFooSelectList()
        {
            return fooRepository.GetAll().ToSelectList(foo => foo.Id, foo => x.Name);
        }
    }
    

    You can use this methods in the controller:

    public class HomeController : BaseController
    {
        public ActionResult ActionX()
        {
            // Creates a new MyVM.
            MyVM myVm = PrepareViewModel();     
        }
    
        public ActionResult ActionY()
        {
            // Update an existing MyVM object.
            var myVm = new MyVM
                           {
                               Property1 = "Value 1",
                               Property2 = DateTime.Now
                           };
            PrepareViewModel(myVm);
        }
    }
    

提交回复
热议问题