s.k.Soni
s.k.Soni

Reputation: 1310

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value using ajax in mvc

When I am sending data from ajax to the controller at that time it showing the title error. While when I am check the datetime that also coming right only. It showing the current datetime only. Still showing the same error.

I know that the same questions is already ask but then also their answer is not solving my issue.

Here is my code

This is my ajax code

var currentdate = new Date();
var utc = new Date(currentdate.getTime())
$.ajax({
    type: "POST",
    url: "/Branch/Save",
    data: JSON.stringify({ Branch: txtBranch.val(), Address: txtAddress.val(), ContactName: txtContactName.val(), Contactno: txtContactNo.val(), PinNo: txtPin.val(), RegistrationNo: txtReg.val(), GSTNo: txtGST.val(), EnrollNo: txtEnroll.val(), Description: txtDesc.val(), CreatedDateTime: utc, CreatedUserID: 0, UpdatedUserID: 0, UpdatedDateTime: 1/1/1990 }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (r) {
        var row = $("#tblBranch tr:last-child").clone(true);
        AppendRow(row, r.BranchID, r.Branch, r.Address, r.ContactName, r.Contactno, r.PinNo, r.RegistrationNo, r.GSTNo, r.EnrollNo, r.Description);
        txtBranch.val("");
        txtAddress.val("");
        txtContactName.val("");
        txtContactNo.val("");
        txtPin.val("");
        txtReg.val("");
        txtGST.val("");
        txtEnroll.val("");
        txtDesc.val("");
        },
        failure: function () {
            alert(txtReg.val());
        }
    });
});

This is my controller code

[HttpPost]
public JsonResult Save(BranchRegistration branchRegistration)
{
    using (BranchContext entities = new BranchContext())
    {
        entities.branch.Add(branchRegistration);
        entities.SaveChanges();
    }

    return Json(branchRegistration);
}

Upvotes: 0

Views: 109

Answers (1)

Shyju
Shyju

Reputation: 218732

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

You usually get this error when your database column is DateTime (not nullable) and your code is not properly setting the value for those column and trying to save it.

This part of your data object,

UpdatedDateTime: 1/1/1990 

will send the payload like

UpdatedDateTime":0.0005025125628140704

Which cannot be converted to a valid DateTime object.

Ideally you should be setting these dates in the server, just before saving

[HttpPost]
public JsonResult Save(BranchRegistration branchRegistration)
{
    branchRegistration.CreatedDateTime =  DateTime.UtcNow;
    branchRegistration.UpdatedDateTime =  DateTime.UtcNow;
    using (var entities = new BranchContext())
    {
        entities.branch.Add(branchRegistration);
        entities.SaveChanges();
    }

    return Json(branchRegistration);
}

Upvotes: 1

Related Questions