Pass SelectedValue of DropDownList in Html.BeginForm() in ASP.NEt MVC 3

前端 未结 1 1080
天涯浪人
天涯浪人 2020-12-17 07:05

This is my View Code:

@using(Html.BeginForm(new { SelectedId = /*SelectedValue of DropDown*/ })) {

 
1条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 07:30

    The selected value will be passed when the form is submitted because the dropdown list is represented by a }

    This assumes the following view model:

    public class MyViewModel
    {
        [DisplayName("Select a category")]
        public int SelectedId { get; set; }
    
        public IEnumerable CategoryList { get; set; }
    }
    

    that will be handled by your controller:

    public ActionResult Index()
    {
        var model = new MyViewModel();
        // TODO: this list probably comes from a repository or something
        model.CategoryList = new[]
        {
            new SelectListItem { Value = "1", Text = "category 1" },
            new SelectListItem { Value = "2", Text = "category 2" },
            new SelectListItem { Value = "3", Text = "category 3" },
        };
        return View(model);
    }
    
    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // here you will get the selected category id in model.SelectedId
        return Content("Thanks for selecting category id: " + model.SelectedId);
    }
    

    0 讨论(0)
提交回复
热议问题