我對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" />
任何幫助將不勝感激,謝謝
用戶如何選擇日期?你能展示視圖嗎? –
@Heyyou請參閱編輯 – coto2
[格式datetime在asp.net mvc 4]可能的重複(http://stackoverflow.com/questions/11272851/format-datetime-in-asp-net-mvc-4) –