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

无人久伴 提交于 2019-12-10 10:52:13

问题


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:


回答1:


As per the comment,

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

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.

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

Now in your view,

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

And in your HttpPost action,

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


来源:https://stackoverflow.com/questions/36379535/how-to-properly-send-selectedvalue-of-dropdownlist-from-view-to-controller-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!