[英]Preventing ASP.Net JSON from dropping trailing 0 in decimal properties
I am using the built in ASP.Net return JSON()
function to convert a View Model to JSON, in this View Model one of the properties is a decimal
. 我正在使用内置的ASP.Net
return JSON()
函数将视图模型转换为JSON,在此视图模型中,属性之一是decimal
。 When this property is filled with a value like 4.50
or 4.00
I have noticed that the JSON version of the View Model is dropping the trailing 0(s). 当此属性填充有
4.50
或4.00
类的值时,我注意到JSON版本的视图模型将删除尾随的0(s)。 How do I stop this behavior so when I read the data in the JavaScript in the View I get all the 0s? 如何停止这种行为,以便在View的JavaScript中读取数据时得到全0?
ViewModel: 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 code that returns the JSON: 返回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 code I am using to check the value: 我用来检查值的JavaScript代码:
$.ajax({
type: "POST",
url: "/TimeCard/TimeCardEntry",
data: { timeCardID: args.row["uid"] },
success: function (data)
{
alert(data["HoursWorked"]);
}
});
Why not just format the result in JavaScript using .toFixed() : 为什么不只使用.toFixed()在JavaScript中格式化结果:
$.ajax({
type: "POST",
url: "/TimeCard/TimeCardEntry",
data: { timeCardID: args.row["uid"] },
success: function (data)
{
var formattedHours = data.HoursWorked.toFixed(2);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.