You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS与ASP.NET MVC日期转换异常:控制器收到1/1/0001

Fixing Date Submission Issue Between AngularJS and ASP.NET MVC

Let's break down why your date is showing up as 1/1/0001 in the controller and how to fix it, while ensuring the date displays as dd-mm-yyyy in the frontend.

Root Cause

The main issues are:

  1. Your AngularJS filter has a bug in parsing the /Date(ticks)/ format into a valid Date object.
  2. When submitting the Date object to ASP.NET, AngularJS serializes it into a human-readable string (like Wed Sep 20 2023 12:34:56 GMT+0530), which the ASP.NET model binder can't parse correctly, so it defaults to the minimum DateTime value (1/1/0001).

Step 1: Fix the AngularJS Date Parsing Filter

Your current filter passes the entire match array to the Date constructor, which is incorrect. Update it to use the captured timestamp value:

myApp.filter("DateOfBirth", function () { 
    var re = /\/Date\(([0-9]*)\)\//; 
    return function (x) { 
        if (!x) return null;
        
        var m = x.match(re); 
        if (m && m[1]) {
            // Parse the timestamp from the captured group
            var timestamp = parseInt(m[1], 10);
            return new Date(timestamp); 
        } else {
            // Fallback for already parsed date strings
            var date = new Date(x);
            return isNaN(date.getTime()) ? null : date;
        }
    }; 
});

Step 2: Display Date as dd-mm-yyyy in the UI

Use AngularJS's built-in date filter to format the Date object for display:

<!-- For read-only display -->
<p>Date of Birth: {{ DateOfBirth | date:'dd-MM-yyyy' }}</p>

<!-- For input fields (use a date picker or formatted input) -->
<input type="text" ng-model="DateOfBirth" ng-value="DateOfBirth | date:'dd-MM-yyyy'" />

For better input handling, consider using an AngularJS date picker directive (like AngularUI Bootstrap's datepicker) which natively works with Date objects and supports custom formatting.


Step 3: Serialize Date Correctly for ASP.NET Submission

Before sending the data to the server, convert the Date object into an ISO 8601 string (a format ASP.NET's model binder recognizes reliably). Modify your submission logic:

$scope.SaveEmployee = function() {
    // Prepare the employee data for submission
    var employeeData = {
        Employee_ID: document.getElementById("EmployeeID_").value,
        First_Name: $scope.FirstName,
        Last_Name: $scope.LastName,
        Country_ID: $scope.counter,
        State_ID: $scope.Counter,
        City_ID: $scope.CityID,
        Email: $scope.Email,
        Password: $scope.Password,
        // Convert Date object to ISO string for ASP.NET
        DateOfBirth: $scope.DateOfBirth instanceof Date ? $scope.DateOfBirth.toISOString() : null,
        Mobile: $scope.Mobile,
        Age: $scope.Age
    };

    // Send data to the controller
    $http.post('/Employee/Update_Data', employeeData)
        .then(function(response) {
            alert(response.data);
            // Reset form or refresh data here
        }, function(error) {
            alert("Error updating employee data");
        });
};

Step 4: Optimize ASP.NET Controller Code

Your controller code has redundant Convert.ToDateTime if the model binder already parses the date correctly. Update it to:

public string Update_Data(Employee employee) {
    if(employee != null) {
        Employee employeeObject = projectContext.Employees
            .FirstOrDefault(x => x.Employee_ID == employee.Employee_ID);
        
        if(employeeObject != null) {
            employeeObject.First_Name = employee.First_Name;
            employeeObject.Last_Name = employee.Last_Name;
            employeeObject.Country_ID = employee.Country_ID;
            employeeObject.State_ID = employee.State_ID;
            employeeObject.City_ID = employee.City_ID;
            employeeObject.Email = employee.Email;
            employeeObject.Password = employee.Password;
            employeeObject.Mobile = employee.Mobile;
            // No need for Convert.ToDateTime if model binder works correctly
            employeeObject.DateOfBirth = employee.DateOfBirth;
            employeeObject.Age = employee.Age;
            
            projectContext.SaveChanges();
            return "Data Updated";
        } else {
            return "Employee not found";
        }
    } else {
        return "Please Check!!";
    }
}

Step 5: Verify the Payload

Use your browser's DevTools (Network tab) to check the request payload. Ensure DateOfBirth is sent as an ISO string like 2023-09-20T00:00:00.000Z—this confirms the serialization is working correctly.

Content of the question来源于stack exchange,提问作者Kasturi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:21:41