[英]Get drop down list default selected item is not passing to the controller in Asp.net MVC
當用戶(編輯事件) 顯示時間下拉列表和日期文本框時 ,我遇到問題。
但是, 當用戶提交表單時,edit操作不會收到舊的時間值。 如果用戶更改時間值,此代碼可以正常工作,它將獲得該值。 除此以外。 它不會。
請幫我。
**編碼**
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:字符串,僅顯示在視圖中。
StartDate / EndDate:db中的dateTime類型。
如果StartTime
的值與SelectList
中的屬性之一不匹配,則在回發時select的值將為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" })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.