Reputation: 6781
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
. 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). How do I stop this behavior so when I read the data in the JavaScript in the View I get all the 0s?
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:
{
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:
$.ajax({
type: "POST",
url: "/TimeCard/TimeCardEntry",
data: { timeCardID: args.row["uid"] },
success: function (data)
{
alert(data["HoursWorked"]);
}
});
Upvotes: 1
Views: 109
Reputation: 9881
Why not just format the result in JavaScript using .toFixed():
$.ajax({
type: "POST",
url: "/TimeCard/TimeCardEntry",
data: { timeCardID: args.row["uid"] },
success: function (data)
{
var formattedHours = data.HoursWorked.toFixed(2);
}
});
Upvotes: 3