我有一个名为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将选定日期[dateofprog]显示为" 14/02 / 2015" [示例]但不会将其分配给模型。究竟问题在哪里我无法解决。谁能帮帮我呢?
答案 0 :(得分:1)
您发布的dateofprogram
格式无效。它表示绑定过程失败。您必须在system.web
的{{1}}部分指定文化才能获得从json解析的正确日期,例如:
web.config
上面的代码告知应用程序的文化,然后如果我以BR格式通知<globalization uiCulture="pt-BR" culture="pt-BR" />
,如dd / MM / yyyy,它将正确绑定。