![](/img/trans.png)
[英]How can I send DropDownList's SelectedValue to the Controller from View with BeginForm?
[英]How to properly send SelectedValue of DropDownList from View to controller? ViewModel
我已經嘗試了許多解決方案,例如this , this和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>
}
如何通過單擊按鈕將View的DropDownList的SelectedValue正確發送到控制器? 是否可以在沒有AJAX
情況下發送值並創建POST
方法? 如果不可能的話,可以使用AJAX
或POST
方法。
我想要的是:
我想要DropDownListFor
,在這里我只能選擇一個DateTime
值,該值可以發送到ActionResult List()
。
我可以看到所有DateTime
值:
根據評論,
我想要DropDownListFor,在這里我只能選擇一個可以發送到ActionResult List()的DateTime值
由於只想選擇一項,因此不需要數組。 還要將您的類型( 獲取所選項目的屬性的類型)更改為有效類型,以便Model綁定能夠將日期(字符串)值映射到視圖模型的屬性。
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.