防止ASP.Net JSON在十进制属性中删除尾随0

时间:2016-10-07 14:58:42

标签: javascript c# asp.net json asp.net-mvc

我使用内置的ASP.Net return JSON()函数将视图模型转换为JSON,在此视图模型中,其中一个属性是decimal。当此属性填充了4.504.00之类的值时,我注意到View Model的JSON版本正在删除尾随的0(s)。我如何阻止这种行为,所以当我在View中读取JavaScript中的数据时,我得到所有的0?

视图模型:

public class TimeCardEntryVM
{
    public int ID { get; set; }
    public string ProjectCode { get; set; }
    public string ProjectDescription { get; set; }
    public string TaskCode { get; set; }
    public string TaskDescription { get; set; }
    public bool IsDurationTime { get; set; }
    public decimal HoursWorked { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public string WorkDescription { get; set; }
}

返回JSON的ASP.Net代码:

{
    var timeEntryData = db.TimeCards
                            .Include(timeCard => timeCard.Project)
                            .Include(timeCard => timeCard.Task)
                            .Where(timeCard => timeCard.ID == timeCardID)
                            .Select(timeCard => new TimeCardEntryVM()
                            {
                                ID = timeCard.ID,
                                EndTime = timeCard.EndDateTime,
                                ProjectCode = timeCard.Project.Code,
                                ProjectDescription = timeCard.Project.Description,
                                StartTime = timeCard.StartDateTime,
                                TaskCode = timeCard.Task.Code,
                                TaskDescription = timeCard.Task.Description,
                                HoursWorked = (decimal)timeCard.TimeWorked,
                                IsDurationTime = timeCard.IsDurationTime,
                                WorkDescription = timeCard.WorkDescription
                            }).First();

    return Json(timeEntryData, JsonRequestBehavior.AllowGet);
}

我用来检查值的JavaScript代码:

$.ajax({
    type: "POST",
    url: "/TimeCard/TimeCardEntry",
    data: { timeCardID: args.row["uid"] },
    success: function (data)
    {
        alert(data["HoursWorked"]);
    }
});

1 个答案:

答案 0 :(得分:3)

为什么不使用.toFixed()格式化JavaScript中的结果:

$.ajax({
    type: "POST",
    url: "/TimeCard/TimeCardEntry",
    data: { timeCardID: args.row["uid"] },
    success: function (data)
    {
        var formattedHours = data.HoursWorked.toFixed(2);
    }
});