I've tried many solutuons, for example this, this and this. However, it does not work cause other examples use ViewBag
, but I am using ViewModel
.
I have ScheduleViewModel
:
public class ScheduleViewModel
{
public int[] SelectedValues { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
public Schedule OneSchedule { get; set; }
}
Controller action 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);
}
and View:
model CinemaAppl.WebUI.Models.ScheduleViewModel
@using (Html.BeginForm())
{
<p>
@Html.DropDownListFor(m => m.SelectedValues, Model.Values)
<input type="submit" value="Filter" />
</p>
}
How to properly send SelectedValue of DropDownList from View to controller by Button click? Is it possible to send values without AJAX
and creating POST
method? If it is not possible, it is okay to use AJAX
or POST
approaches.
What I want is:
I want DropDownListFor
where I can choose just one DateTime
value which I can send to ActionResult List()
.
I can see all DateTime
values:
As per the comment,
Since you want to select only one item, you do not need an array. Also change your type (of the property which gets the selected item) to a valid type so that Model binding will be able to map the date (string) value to the property of your view model.
Now in your view,
And in your HttpPost action,