0

Controller Code :

public ActionResult Index()
{
PersonRepository repo = new PersonRepository();
PersonListModel lstPersons = new PersonListModel();
lstPersons.Persons = repo.GetAllPerson();
return View(lstPersons);
}

Actual Javascript Code :

<script type="text/javascript"> 

var personListData = @Html.Raw(Json.Encode(Model.Persons));

var viewModel = {
personsModel : ko.observableArray(personListData)

}

ko.applyBindings(viewModel)

<script/> 

Result while Debugigng :

 var personListData = [
  {"PersonId":324783035204000026,"FirstName":"Gibbbs","BirthDate":"\/Date(1347647400000)\/"},{"PersonId":324126155204000001,"FirstName":"Russel","BirthDate":"\/Date(1347561000000)\/"}];

*Question :

  1. when the model data get bindinng it will show me person id as : 324783035204000026 but when the binding process get complete it make change into PersonId as : 324783035204000000 and 324126155204000001 to 324126155204000000

  2. Date data is also not binding properly.

so what is the main reason behind it ?

please help me if you have any idea about this.

Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
Ajay
  • 1
  • 1

1 Answers1

1
  1. The number 324783035204000026 is too large to be accurately represented by JavaScript, so the last two digits are getting dropped. You can fix this by making the PersonId property in your PersonListModel class a string, rather than a decmial, or whatever it currently is.

    If you cannot modify the PersonListModel class, for whatever reason, you should create a new class, called something like PersonListModelClient, that has the subset of properties you need for your JavaScript code, and then copy the data from each PersonListModel into a new instance of PersonListModelClient, then encode them as JSON instead.

  2. This is because dates have no standard representation in JSON, so Microsoft invented a format, that looks like "\/Date(1347647400000)\/", where a date is encoded into a string. You have two options: If you just want to display the date to the user,you can use the same approach as before, and change the BirthDate property into a string, and do the formatting on the server side using the DateTime.ToString method. Alternatively, you can use the answer to this question, which shows how to convert the specially formatted string into a regular JavaScript Date object.

Community
  • 1
  • 1
Jon Rimmer
  • 12,064
  • 2
  • 19
  • 19