How to use knockout.js with ASP.NET MVC ViewModels?

How to use knockout.js with ASP.NET MVC ViewModels?

Asked on November 14, 2018 in knockout js.
Add Comment

  • 2 Answer(s)

        Try this code to serialize the ASP.NET MVC view model into a javascript variable:

    @model CourseVM
    <script type="text/javascript">
      var model = @Html.Raw(Json.Encode(Model));
      // go ahead and use the model javascript variable to bind with ko

        Get many of examples in the knockout documentation.

    Answered on November 14, 2018.
    Add Comment

        To achieve the more computed properties after server mapping enhance further the  viewmodels on the client side.

    For ex:

    var viewModel = ko.mapping.fromJS(model);

    viewModel.capitalizedName = ko.computed(function() {...}, viewModel);

        So everytime get the information from raw JSON,  reapply the computed properties is must.

        Moreover the mapping plugin provides the ability to incrementally update a viewmodel as opposed to recreating it all the time you go front and back :

    // Every time data is received from the server:
    ko.mapping.fromJS(data, viewModel);

        And that executes an additional data update on the model of just properties that are mapped.  read more about that is possible in the mapping documentation

        This case is more specific than ko.mapping.   Use it only if the viewmodels are one way (ie. server -> client) and then data is posted back in some different format (or not at all).

      Or if  javascript viewmodel needs to be in a substantially different format from your server model.

    Answered on November 14, 2018.
    Add Comment

  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.