2015-09-12 215 views
1

我對MVC和C#非常陌生,我正嘗試創建一個預訂系統,以便當用戶選擇Practice,Optician和Date時,JSON查詢返回可用時間。Ajax查詢下拉列表不填充

我的視圖模型:

public class BookingViewModel 
{ 
    [Display (Name = "Select Patient")] 
    public Guid PatientId { get; set; } 
    public IEnumerable<SelectListItem> PatientList { get; set; } 

    [Display(Name = "Select Practice")] 
    public Guid PracticeId { get; set; } 
    public IEnumerable<SelectListItem> PracticeList { get; set; } 

    [Display(Name = "Select Optician")] 
    public Guid OpticianId { get; set; } 
    public IEnumerable<SelectListItem> OpticiansList { get; set; } 

    [Display(Name = "Select Date")] 
    [DataType(DataType.Date)] 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] 
    public DateTime Date { get; set; } 

    [Display(Name = "Select Time")] 
    public Guid TimeId { get; set; } 
    public IEnumerable<SelectListItem> TimeList { get; set; }  
} 

控制器:

public ActionResult Create() 
    { 
     // Creates a new booking 
     BookingViewModel bookingViewModel = new BookingViewModel(); 
     // Initilises Select List 
     ConfigureCreateViewModel(bookingViewModel); 

     return View(bookingViewModel); 

    } 

    // Initilises Select List 
    public void ConfigureCreateViewModel(BookingViewModel bookingViewModel) 
    { 
     // Displays Opticians Name 
     bookingViewModel.OpticiansList = db.Opticians.Select(o => new SelectListItem() 
     { 
      Value = o.OpticianId.ToString(), 
      Text = o.User.FirstName 
     }); 

     // Displays Patients name 
     bookingViewModel.PatientList = db.Patients.Select(p => new SelectListItem() 
     { 
      Value = p.PatientId.ToString(), 
      Text = p.User.FirstName 
     }); 

     // Displays Practice Name 
     bookingViewModel.PracticeList = db.Practices.Select(p => new SelectListItem() 
     { 
      Value = p.PracticeId.ToString(), 
      Text = p.PracticeName 
     }); 

     // Displays Appointment Times 
     bookingViewModel.TimeList = db.Times.Select(t => new SelectListItem() 
     { 
      Value = t.TimeId.ToString(), 
      Text = t.AppointmentTime 
     }); 


    } 


    // Allows Admin to create booking for patient 
    // POST: Bookings1/Create 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(BookingViewModel bookingViewModel) 
    { 
     // to ensure date is in the future 
     if (ModelState.IsValidField("Date") && DateTime.Now > bookingViewModel.Date) 
     { 
      ModelState.AddModelError("Date", "Please enter a date in the future"); 
     }   

     // if model state is not valid 
     if (!ModelState.IsValid) 
     { 
      // Initilises Select lists 
      ConfigureCreateViewModel(bookingViewModel); 
      return View(bookingViewModel); // returns user to booking page 

     } 
     else // if model state is Valid 
     { 
      Booking booking = new Booking(); 
      // Sets isAvail to false 
      booking.isAvail = false; 
      booking.PracticeId = bookingViewModel.PracticeId; 
      booking.OpticianId = bookingViewModel.OpticianId; 
      booking.PatientId = bookingViewModel.PatientId; 
      booking.Date = bookingViewModel.Date; 
      booking.TimeId = bookingViewModel.TimeId; 

      // Generates a new booking Id 
      booking.BookingId = Guid.NewGuid(); 
      // Adds booking to database 
      db.Bookings.Add(booking); 
      // Saves changes to Database 
      db.SaveChanges(); 
      // Redirects User to Booking Index 
      return RedirectToAction("Index"); 
     } 
    } 

JSON查詢返回可用時間:

// Json to return Availiable times 
    [HttpPost] 
    public JsonResult AvailTimes(Guid practiceId, Guid opticianId, DateTime date) 
    { 
     var timesList = db.Bookings.Where(a => a.PracticeId == practiceId) 
            .Where(a => a.OpticianId ==opticianId) 
            .Where(a => a.Date == date) 
            .Where(a => a.isAvail != false) 
            .Select(a => new 
     { 
      Value = a.TimeId, 
      Text = a.Time.AppointmentTime 
     }).ToList(); 

     return Json(timesList); 
    } 

Ajax來填充時間:

<script> 
$(document).ready(function() { 
    var times = $("#TimeId"); // Cache Time element 
    times.prop("disabled", true); 
    $("#PracticeId","#OpticianId","#Date").change(function() { 
     $.ajax({ 
      url: "@Url.Action("AvailTimes","Bookings")", 
      type: "POST", 
      data: { Id: $(this).val() } 
     }).done(function (timesList) { 
      console.log(timesList) 
      times.empty(); 
      for (var i = 0; i < timesList.length; i++) { 
       times.append("<option value=" + timesList[i].Value + ">" + timesList[i].Text + "</option>"); 
      } 
      times.prop("disabled", false); 
     }); 
    }); 
}); 
</script> 

查看:

<div class="form-group"> 
     @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" }) 
     </div> 
    </div> 

訂票時作出IsAvail設置爲false,所以我試圖用我的JSON LINQ查詢做的是返回可用的齒

然而,當我選擇練習,配鏡師和日期時間仍然禁用。我檢查了控制檯並收到以下警告:

指定值'01/01/0001'不符合所需格式'yyyy-MM-dd'。

<input class="form-control text-box single-line" data-val="true" data-val-date="The field Select Date must be a date." data-val-required="The Select Date field is required." id="Date" name="Date" type="date" value="01/01/0001" /> 

任何幫助將不勝感激,謝謝

+0

用戶如何選擇日期?你能展示視圖嗎? –

+0

@Heyyou請參閱編輯 – coto2

+0

[格式datetime在asp.net mvc 4]可能的重複(http://stackoverflow.com/questions/11272851/format-datetime-in-asp-net-mvc-4) –

回答

1

那麼,有在你的代碼的一些問題。

第一:

然而,當我選擇一個實踐,配鏡和日期時間仍然 禁用。我檢查了控制檯,我得到以下警告:

如果日期時間輸入無效(空),這意味着你發送一個「零」日期時間值到控制器。由於日期時間不能爲空,因此它採用默認值,即「0001/01/01」。

爲了解決這個問題,你可以使用一個可以爲空日期時間參數,就像這樣:

[HttpPost] 
public JsonResult AvailTimes(Guid practiceId, Guid opticianId, DateTime? date) 
{ 
    var timesList = db.Bookings 
      .Where(a => a.PracticeId == practiceId && 
        a.OpticianId ==opticianId &&) 
        a.isAvail != false &&); 

    if (date.HasValue) 
     timesList = timesList.Where(i => i.Date == date.Value); 

    var final = timesList.Select(a => new 
    { 
     Value = a.TimeId, 
     Text = a.Time.AppointmentTime 
    }).ToList(); 

    return Json(final); 
} 

二:

在您看來,您使用的日期比不同格式的en-US文化。

EN-US:MM/DD/YYYY

您的格式(通常在南美洲使用):DD/MM/YYYY

如果您的服務器使用EN-US區域性,這通常是默認情況下,它可能無法識別你的日期。

你有幾種選擇。您可以將您的日期作爲字符串發送,並使用特定的文化進行分析。像這樣:

[HttpPost] 
public JsonResult AvailTimes(Guid practiceId, Guid opticianId, string date) 
{ 
    var timesList = db.Bookings 
      .Where(a => a.PracticeId == practiceId && 
        a.OpticianId ==opticianId &&) 
        a.isAvail != false &&); 

    if (!string.IsNullOrWhiteSpace(date)) { 
     System.Globalization.CultureInfo yourCulture = 
     new System.Globalization.CultureInfo("pt-BR"); //example 
     DateTime yourDate = DateTime.Parse(date, yourCulture); 
     timesList = timesList.Where(i => i.Date == yourDate); 
    } 

    var final = timesList.Select(a => new 
    { 
     Value = a.TimeId, 
     Text = a.Time.AppointmentTime 
    }).ToList(); 

    return Json(final); 
} 

另一種完成此操作的方法是更改​​整個線程/應用程序的文化。所以,MVC模型綁定器會自動識別你的日期格式,不需要解析。

還有其他技術可用於處理Web應用程序中的日期格式。如果您的應用程序僅通過一種文化訪問,您可能不會遇到任何問題。但是,如果您的應用程序被多種文化訪問,我建議您在互聯網上閱讀有關日期時間技術的更多信息。

+0

感謝您的回答,但是我已經嘗試了兩種方法,而且我仍然收到以下錯誤'指定值'01/01/01'不符合要求格式,'yyyy-MM-dd'。' – coto2

+0

您的輸入是將該值發送給控制器。它必須爲空或有效日期。請記住將日期參數更改爲字符串。 –