我对MVC和C#非常陌生,我正在尝试创建一个预订系统,以便当用户选择练习,配镜师和日期时,JSON查询会返回可用时间。
我的视图模型:
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查询返回可用的时间
但是,当我选择练习,配镜师和日期仍然禁用时间时。我检查了控制台并收到以下警告:
指定值&#39; 01/01/0001&#39;不符合要求的格式,&#39; yyyy-MM-dd&#39;。
<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 :(得分:1)
嗯,您的代码中存在一些问题。
首先:
然而,当我选择练习,配镜师和日期仍然是时间 禁用。我检查了控制台并收到以下警告:
如果禁用DateTime输入(并为空),则表示您正在向控制器发送“null”日期时间值。由于datetime不能为null,因此它采用默认值,即'0001/01/01'。
要解决此问题,您可以使用可为空的datetime参数,如下所示:
[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: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应用程序中的日期格式。如果您的应用程序仅由一种文化访问,您可能不会有任何问题。但是,如果您的应用程序被多种文化访问,我建议您在互联网上阅读有关日期时间技术的更多信息。