如何正确地将 DropDownList 的 SelectedValue 从 View 发送到控制器?视图模型

How to properly send SelectedValue of DropDownList from View to controller? ViewModel

我试过很多解决方案,例如, this and this。但是,它不起作用,因为其他示例使用 ViewBag,但我使用的是 ViewModel.

我有 ScheduleViewModel:

public class ScheduleViewModel
{
    public int[] SelectedValues { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }       
    public Schedule OneSchedule { get; set; }
}

控制器动作List:

    public ActionResult List(ScheduleViewModel scheduleVM)//scheduleVM is always NULL
    {                             
        var model = new ScheduleViewModel();
        IList<SelectListItem> listTime = new List<SelectListItem>();
        DateTime time = DateTime.Today;            
        for (DateTime _time = time; _time < time.AddDays(5); _time = _time.AddDays(1)) //from 16h to 18h hours
        {
            listTime.Add(new SelectListItem() { Value = _time.ToShortDateString(), Text = _time.ToShortDateString() });
        }
        
        model.Values = listTime;
        return View(model);
    }

和视图:

model CinemaAppl.WebUI.Models.ScheduleViewModel


@using (Html.BeginForm())
{
    <p>       
        @Html.DropDownListFor(m => m.SelectedValues, Model.Values)
        <input type="submit" value="Filter" />
    </p>
}

如何通过单击按钮正确地将 DropDownList 的 SelectedValue 从视图发送到控制器? 是否可以在没有 AJAX 和创建 POST 方法的情况下发送值?如果不行,用AJAXPOST方法也可以。

我要的是:

我想要 DropDownListFor 我可以只选择一个 DateTime 值,我可以发送到 ActionResult List().

我可以看到所有 DateTime 个值:

根据评论,

I want DropDownListFor where I can choose just one DateTime value which I can send to ActionResult List()

由于您只想 select 一项,因此不需要数组。还要将您的类型(属性 的 获取 selected 项目 )更改为有效类型,以便模型绑定能够映射日期(字符串) 值到视图模型的 属性。

public class ScheduleViewModel
{
    public DateTime? SelectedDate { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }       
    public Schedule OneSchedule { get; set; }
}

现在在您看来,

@model ScheduleViewModel
@using(Html.BeginForm())
{
   @Html.DropDownListFor(x => x.SelectedDate, Model.Values)
   <input type="submit" />
}

并且在您的 HttpPost 操作中,

[HttpPost]
public ActionResult List(ScheduleViewModel model)
{
   if(model.SelectedDate!=null)  
   {
     //Safe to access model.SelectedDate.Value now :)
   }
   // to do : Return something
}