从ajax中为传递为null的日期值绑定模型

model binding from ajax for date value passing as null

本文关键字:日期 绑定 模型 ajax null      更新时间:2023-10-15

我有一个名为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.configsystem.web部分中指定区域性,才能从json中获得正确的解析日期,例如:

<globalization uiCulture="pt-BR" culture="pt-BR" />

上面的代码通知了应用程序的区域性,如果我以类似dd/MM/yyyy的BR格式通知DateTime,它将正确绑定。