ViewModel getting null values in action method

后端 未结 2 1700
北海茫月
北海茫月 2020-12-10 18:49

I am using a ViewModel to retrieve entered data in controller action. But the ViewModel is getting empty values in it\'s properties. I am creating one partial view

2条回答
  •  一向
    一向 (楼主)
    2020-12-10 19:20

    This answer will not solve your problem directly, but first of all I recommend you to outsource the filling of the ViewModel at least to the controller (Because otherwise it will recreate the DBContext every time the constructor is called). A ViewModel should only contain data - no logic. And secoundly I would use the DBContext in an Using statement

    ViewModel:

    public class LookUpViewModel
        {    
            [Required]
            public virtual IEnumerable tblCurrentLocations { get; set; }
    
            [Required]
            public virtual IEnumerable tblStreams {  get;  set; }
    

    Controller:

    public ActionResult Foo()
    {
        LookUpViewModel ViewModel = new LookUpViewModel();
        using(RosterManagementEntities rosterManagementContext = new RosterManagementEntities())
        {
            ViewModel.tblCurrentLocations = from o in rosterManagementContext.tblCurrentLocations select o;
            ViewModel.tblStreams = from o in rosterManagementContext.tblStreams select o; 
        }
    
        return View(ViewModel);
    }
    

提交回复
热议问题