获取下拉列表默认选中的项目未传递给Asp.net MVC中的控制器

时间:2014-09-13 05:34:27

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我在用户(编辑活动)时遇到问题显示时间下拉列表,以及日期文本框。

当用户提交表单时,编辑操作未收到旧值的时间。 如果用户更改时间值,此代码可以正常工作,它将获得该值。除此以外。它不会。

请帮助我。

**代码**

Html.DropDownListFor(x=>x.StartTime, Model.Times,
Model.Appointment.StartDate.ToString("hh:mm tt"), new {@class = "dropdownlist" })

public ActionResult Edit(int id = 0){
    Appointment app = eventService.GetEventByID(id);
   EventViewModel model = new EventViewModel() 
    { Appointment =app,
     StartTime = app.StartDate.ToString("hh:mm tt"),
      EndTime = app.EndDate.ToString("hh:mm tt"),
      Times = TimesSelectListItem, };

// Get the time portion of our date/time from our drop down lists
   DateTime startTime = Convert.ToDateTime(model.StartTime);
   DateTime endTime = Convert.ToDateTime(model.EndTime);

 // Create a new date based on the date from our date picker, and time from our drop down lists:
model.Appointment.StartDate = new DateTime(model.Appointment.StartDate.Year, model.Appointment.StartDate.Month, model.Appointment.StartDate.Day, startTime.Hour, startTime.Minute, startTime.Second);
model.Appointment.EndDate = new DateTime(model.Appointment.EndDate.Year, model.Appointment.EndDate.Month, model.Appointment.EndDate.Day, endTime.Hour, endTime.Minute, endTime.Second);

 if (model == null)   {
  return HttpNotFound();   }

PopulatePriorityDropDownList(model.Appointment.FK_PriorityID);
 PopulatePrivacyDropDownList(model.Appointment.FK_PrivacyID);
PopulateTypeDropDownList(model.Appointment.FK_AppointmentTypeID);
       return View(model);
  }


   [HttpPost]
   [ValidateAntiForgeryToken]
   public ActionResult Edit(EventViewModel model, int id, string PriorityID, string PrivacyID, string TypeID)
            {
//------------
this is in the controler...
   IEnumerable<SelectListItem> TimesSelectListItem = new[] {
                new SelectListItem{ Text="6:00 AM", Value = "6:00 AM" },
                new SelectListItem{ Text="6:30 AM", Value = "6:30 AM" },....etc}

StartTime / StartTime:string,仅显示在视图中。
StartDate / EndDate:db。中的dateTime类型。

1 个答案:

答案 0 :(得分:0)

如果StartTime的值与SelectList中的某个属性不匹配,那么selectback的值在回发时将为null,因为您在DropDownListFor()中使用了选项标签(这会呈现一个没有价值的选项。)

检查StartTime的值是否与其中一个选项的值完全匹配。

如果始终设置初始值,则删除DropDownListFor()方法

的3参数
@Html.DropDownListFor(x=>x.StartTime, Model.Times, new {@class = "dropdownlist" })

否则,将其设为用户友好消息,以便用户明确选择

Html.DropDownListFor(x=>x.StartTime, Model.Times, "Please select a time"), new {@class = "dropdownlist" })