简体   繁体   English

基于Lambda表达式的基于属性的帮助程序,用于数据绑定,以将Knockout.js与MVC4 / 5 + Razor集成

[英]Attribute-based helper with lambda expressions for data-bind for integrating knockout.js with MVC4/5 + Razor

I just tried KnockoutMvc and while I admire the creator's effort, I find it is a little too heavy-handed to be useful in general. 我只是尝试了KnockoutMvc ,在欣赏创作者的努力的同时,我发现它有点笨拙,无法普遍使用。 However I like to minimize the amount of JavaScript in my Razor views, especially boilerplate JavaScript (like binding my serverside view models to clientside view models). 但是,我想尽量减少Razor视图中的JavaScript数量,尤其是样板JavaScript(例如将服务器端视图模型绑定到客户端视图模型)。

Is there any library out there that allows you to use syntax like: 是否有任何库可让您使用如下语法:

<span data-bind="@Html.DataBindFor(m => m.MyProperty)"></span>

Alternatively, if I were to go about trying to write my own, approximately what (very general) components would I need to make the library useful? 另外,如果我要尝试编写自己的库,大约需要什么(非常通用)的组件才能使该库有用? I am assuming at a minimum I would need: 我假设我至少需要:

  1. A custom set of attributes for defining how each model / property / method would be bound 一组自定义属性,用于定义每个模型/属性/方法的绑定方式
  2. An extension method for use in Razor views to use reflection to find out the attribute values 在Razor视图中使用的一种扩展方法,用于使用反射来找出属性值
  3. An extension method for use in Razor to generate the (minimal?) JavaScript to bind the client view model to the Razor Model and functions to call the server while necessary Razor中用于生成(最小?)JavaScript的扩展方法,以将客户端视图模型绑定到Razor模型,并在必要时调用服务器功能

Finally, assuming this library doesn't exist, is there a good reason it doesn't exist? 最后,假设该库不存在,是否有充分的理由不存在该库? IE is there no way to really work this problem in generality such that a helper method is, uh, helpful? IE没有办法真正普遍地解决此问题,因此,辅助方法对您有帮助吗?

The reason I ask is because the library Lib.Web.Mvc.JqGrid has helped me create interactive tables really quickly with absolutely minimal amounts of JavaScript (just enough to format columns and such) and I wonder why the same does not exist for knockout.js . 我问的原因是因为Lib.Web.Mvc.JqGrid库帮助我使用绝对少量的JavaScript(足以格式化列等)真正快速地创建了交互式表,我想知道为什么没有相同的knockout.js

The get rid of manually translating the server-side models to the client-side view models, you can employ the ko.mapping plugin which is then used like this: 摆脱了手动将服务器端模型转换为客户端视图模型的麻烦 ,您可以使用ko.mapping插件,然后将其像这样使用:

@model ViewModel

<script src="@Url.Content("~/Scripts/knockout.mapping-latest.js")" type="text/javascript"></script>

...

<script type="text/javascript">
    function ViewModel(initData) {
        var self = this;
        ko.mapping.fromJS(initData, {}, self);

        // Add custom view model logic
        ...

        // Logic for persisting the current state of the model back to the server
        self.Save = function() {                
            $.ajax('/model-uri', {
              type: 'POST',
              contentType: "application/json",
              data: ko.toJSON(self),
              success: function (response) {
                  alert('Success!');
              },
              error: function(xhr, status, error) {
                  alert('Error: ' + xhr.responseText);
              }              
         });
    };

    var initialData = @(Html.Raw(JsonConvert.SerializeObject(Model)));
    var model = new ViewModel(initialData);
    ko.applyBindings(model);
</script>

Note that we're serializing the server-provided view model to a JavaScript object and then making its properties observable using the ko.mapping plugin which saves us duplicating the view model definition on the client side. 请注意,我们正在将服务器提供的视图模型序列化为JavaScript对象,然后使用ko.mapping插件使它的属性可观察,这节省了我们在客户端复制视图模型的定义。 We also employ the ko.toJSON utility function when sending the updated model back to the server. 当将更新的模型发送回服务器时,我们还采用了ko.toJSON实用程序功能。

The mapping procedure can be customized to ignore certain properties: 可以自定义映射过程以忽略某些属性:

var mapping = {
    'ignore': ["propertyToIgnore", "alsoIgnoreThis"]
}

ko.mapping.fromJS(data, mapping, self);

There are more mapping customizations available, described on the plugin page . 插件页面上有更多可用的映射自定义项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM