Best practice on passing Mvc Model to KnockoutJS

后端 未结 8 953
独厮守ぢ
独厮守ぢ 2020-12-04 17:12

I googled around on how to pass mvc model to knockoutjs and it seems there are two ways:

  • Using @Html.Raw(Json.Encode(Model))
  • Using $.get or $.ajax
8条回答
  •  自闭症患者
    2020-12-04 17:28

    Old question, but I think I have a nice tidy solution for passing model data to a KO view model, in a reusable fashion. Note, I'm using require.js as well.

    Add the HtmlHelper extension method, in .NET:

    using System.Web;
    using System.Web.Mvc;
    using System.Web.Script.Serialization;
    
    namespace PROJECT.YOUR.EXTENSIONS.NAMESPACE {
    
        public static class HtmlHelperJavascriptExtensions {
    
            public static IHtmlString Serialize(this HtmlHelper helper, object obj) {
                return helper.Raw(new JavaScriptSerializer().Serialize(obj));
            }
        }
    }
    

    Add the partial view, KnockoutJsBinderPartial (I've had to use aspx):

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <%@ Import Namespace="PROJECT.YOUR.EXTENSIONS.NAMESPACE" %>
    
    
    

    The model referenced by that view is:

    namespace PROJECT.Views.Shared {
    
        public class KnockoutJsBinderViewData {
    
            public object InnerModel { get; private set; }
    
            public string ViewModelPath { get; private set; }
    
            public KnockoutJsBinderViewData(object innerModel, string viewModelPath) {
                InnerModel = innerModel;
                ViewModelPath = viewModelPath;
            }
        }
    }
    

    Now, to wire up your .NET model to your knockout view model, all you need to do is:

    <% Html.RenderPartial(
       "~/Views/Shared/KnockoutJsBinderPartial.ascx",
       new PROJECT.Views.Shared.KnockoutJsBinderViewData(
            Model, // The model from your strongly typed MVC view
            "Path/To/Knockout/ViewModel")); // The path to the Javascript file containing your view model
    %>
    

    Note, the Javascript file containing your view model SHOULD NOT call ko.applyBindings and should return the Constructor function for the view model. The constructor should take one argument - your JSON data for the model.

提交回复
热议问题