从ajax中为传递为null的日期值绑定模型
model binding from ajax for date value passing as null
我有一个名为bookprogram的页面,下面是它的模型!
public class BookViewModel
{
[Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)]
[Display(Name="Name *")]
public string name { get; set; }
[Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)]
[DataType(DataType.PhoneNumber)]
public string contact { get; set; }
[Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)]
[RegularExpression("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}", ErrorMessage = "Invalid Email Id")]
public string email { get; set; }
[Required(ErrorMessage = "Please select a category")]
public string category { get; set; }
[Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime dateofprogram { get; set; }
[Required(ErrorMessage = "Field cannot be blank!", AllowEmptyStrings = false)]
[StringLength(200,ErrorMessage="Max length exceeded! Should be less than 200 characters")]
public string Message { get; set; }
}
这是我执行AJAX Post 的js
function ValidateBookProgramAndPost(form)
{
$(form).on("submit", function (e) {
e.preventDefault();
ValidateForm(form);
var selectedVal = $(form).find('select').children(":selected").val();
if(selectedVal=="")
{
$(form).find('div.bootstrap-select').children(":first").addClass('alert-danger');
$(form).find('div.bootstrap-select').next('.text-danger').html('Please select a category!');
}
var dateofprog = moment().format($('#txtDate').val());
console.log(dateofprog);
$.ajax({
url: '/BookProgram/',
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ model:{
name: $('#txtName').val(),
contact: $('#txtPhone').val(),
email: $('#txtEmail').val(),
category: $("#hdnSelectedCategory").val(),
dateofprogram: dateofprog,
Message: $("#txtMessage").val()
}
}),
success: function (data) {
if (data.result) {
$(form).find('input[type=text], textarea').val('').removeClass("alert-success");
$('.selectpicker').selectpicker('refresh');
}
else {
if (data.result == "Email Validation failed on server side!") {
$("#txtEmail").addClass("alert-danger");
}
else {
//display error message
}
return false;
}
return true;
}
}
$(form).unbind('submit');
return false;
});
这是我的控制器:
[HttpPost]
public ActionResult BookProgram(BookViewModel model)
{
bool valid = false;
bool val = false;
if (ModelState.IsValid)
{
if (model.name != "" && model.category != "" && model.contact != "" && model.dateofprogram.ToShortDateString() != "" && model.email != "" && model.Message != "")
{
if (v.validateEmail(model.email) && v.validatePhone(model.contact))
{
valid = true;
}
else
{
return Json(new { result = "Email/Phone Validation failed on server side!" });
}
}
else
{
return Json(new { result = "One of the field has been modified and has been sent empty!!" });
}
if (valid)
{
using (var context = new MConnectionString())
{
tbl_programs book = new tbl_programs();
book.cont = model.contact;
book.date = model.dateofprogram;
book.email = model.email;
book.msg = model.Message;
book.category = model.category;
book.status = "";
book.name = model.name;
context.tbl_programs.Add(book);
context.SaveChanges();
val = true;
}
if (val)
{
return Json(new { result = true });
}
else
{
return Json(new { result = "Could not book the program. Please try again!" });
}
}
return Json(new { result = "Could not book the program. Please try again!" });
}
return Json(new { success = false });
}
但当我在控制器中检查时,日期值为空,Model.IsValid
失败。那么我应该如何从ajax传递日期值呢?Console.log将所选日期[dateofpg]显示为"2015年2月14日"[示例],但不会将其分配给模型。问题在哪里?实际上我搞不清楚。有人能帮我吗??
您发布的dateofprogram
格式无效。它在绑定过程中失败。您必须在web.config
的system.web
部分中指定区域性,才能从json中获得正确的解析日期,例如:
<globalization uiCulture="pt-BR" culture="pt-BR" />
上面的代码通知了应用程序的区域性,如果我以类似dd/MM/yyyy的BR格式通知DateTime
,它将正确绑定。
相关文章:
- 将日期时间javascript绑定到表列
- Angularjs和Jquery日期选择器数据绑定
- 为什么我的AngularJS ngModel绑定到时间输入,而不绑定到日期输入
- 从ajax中为传递为null的日期值绑定模型
- 在选择未绑定到模型 Angular js 的日期值时使用日期选择器
- 将 JSON 数据绑定到日期范围选取器日历
- 如何在引导日期范围选取器日期更改时更新绑定
- 如何将 jQuery 日期选择器中的选定值绑定到挖空可观察量
- 错误绑定引导日期时间选取器到模型角度
- Angularjs ,如何设置输入的 ng 模型以通过自动绑定更改日期和时间
- 根据 Knockout.js 中的复选框绑定将来的日期选择器最大日期
- 在表单提交时将日期的 JavaScript 数组绑定到页面的视图模型
- 角度 :如何将包含日期的选择与角度引导日历绑定
- 如何绑定角度引导的bs日期选择器指令的select事件
- jQuery UI日期选择器绑定
- 是否可以将日期/时间绑定到控制台日志
- 将挖空值绑定到 HTML5 日期选取器 (Chrome)
- 使用Knockout.js如何将Date属性绑定到HTML5日期选择器
- 使用metro.js日期选择器敲除mvvm绑定
- 如何格式化Json日期并将其绑定到DatePicker控件