防止ASP.Net JSON从在十进制属性中删除尾随0
本文关键字:删除 属性 十进制 Net ASP JSON 防止 | 更新日期: 2023-09-27 18:12:07
我正在使用内置的ASP。Net return JSON()
函数将视图模型转换为JSON,在此视图模型中,其中一个属性是decimal
。当这个属性被像4.50
或4.00
这样的值填充时,我注意到视图模型的JSON版本正在删除末尾的0(s)。我如何阻止这种行为,所以当我在视图中读取JavaScript中的数据时,我得到所有的0 ?
ViewModel:
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; }
}
ASP。. Net代码返回JSON:
{
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"]);
}
});
为什么不直接在JavaScript中使用.toFixed():
格式化结果呢?$.ajax({
type: "POST",
url: "/TimeCard/TimeCardEntry",
data: { timeCardID: args.row["uid"] },
success: function (data)
{
var formattedHours = data.HoursWorked.toFixed(2);
}
});