gpt4 book ai didi

c# - 如何正确地将 DropDownList 的 SelectedValue 从 View 发送到 Controller ? View 模型

转载 作者:行者123 更新时间:2023-11-30 20:20:31 26 4
gpt4 key购买 nike

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

我有 ScheduleViewModel:

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

Controller 操作列表:

    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);
}

和 View :

model CinemaAppl.WebUI.Models.ScheduleViewModel


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

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

我想要的是:

我想要 DropDownListFor,在这里我可以只选择一个 DateTime 值,我可以将它发送到 ActionResult List()

我可以看到所有 DateTime 值:

enter image description here

最佳答案

根据评论,

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

由于您只想选择一项,因此不需要数组。同时将您的类型(获取所选项目的属性)更改为有效类型,以便模型绑定(bind)能够将日期(字符串)值映射到 View 模型的属性。 p>

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
}

关于c# - 如何正确地将 DropDownList 的 SelectedValue 从 View 发送到 Controller ? View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36379535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com