asp.net mvc 3 pre-select Html.DropDownListFor not working in nerd dinner

后端 未结 5 2068
一向
一向 2020-12-31 07:19

Learning about dropdown lists, Im trying to add a RSVP create page for nerddinner as in Scott Gu\'s blog with a Html.DropDownListFor listing available dinners.

I ca

5条回答
  •  青春惊慌失措
    2020-12-31 08:15

    After reading here and here, I finally understand how HtmlDropDownlistFor automatically selects the correct item in the dropdown based on your model - selecting a dinnerID in RSVP (foreign key to dinner.dinnerID) will cause the dropdown containing list of Dinner.DinnerIDs to pre select that value. No need yet I think for selectedValue in the SelectList or ViewModel.

    Solution:

        //
        //GET: /RSVP/Create
    
        public ActionResult Create()
        {
            //automatically preselects matching DinnerID in the Dinner dropdownlist            
            var rsvp = new RSVP {DinnerID = 2 };
    
            var typeList = new SelectList(dbc.Dinners.ToList(), "DinnerID", "Title");
            var viewModel = new RSVPViewModel { DinnersList = typeList, Rsvp = rsvp};
    
            return View("Create", viewModel);
        }
    

提交回复
热议问题