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

后端 未结 13 1050
感动是毒
感动是毒 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
    {
        /// <summary>
        /// Prepares a new MyVM by filling the common properties.
        /// </summary>
        /// <returns>A MyVM.</returns>
        protected MyVM PrepareViewModel()
        {
            return new MyVM()
            {
                FooDll = GetFooSelectList();
            }
        }
    
        /// <summary>
        /// Prepares the specified MyVM by filling the common properties.
        /// </summary>
        /// <param name="myVm">The MyVM.</param>
        /// <returns>A MyVM.</returns>
        protected MyVM PrepareViewModel(MyVM myVm)
        {
            myVm.FooDll = GetFooSelectList();
            return myVm;
        }
    
        /// <summary>
        /// Fetches the foos from the database and creates a SelectList.
        /// </summary>
        /// <returns>A collection of SelectListItems.</returns>
        private IEnumerable<SelectListItem> 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题