2

I have a .NET MVC 4 project and just started Kendo UI MVVM framework. MVC uses ViewModels to send data from the controller to the view. I manage all my client side objects via the MVVM framework and use JSON to serialize them and send them back to my controller.

Currently I use the MVC ViewModel to return the data that will be static on my page and use jquery calls to fetch any dynamic data needed on my page. I find it confusing to have 2 methods to retrieve data. (And if I find it confusing, imagine the next developer that will have to work in my code)

I find it a bit useless to send the data to the View via ViewModels when I can easily have a structure where I query the controller (via Web API) on demand in my javascript code and save it into my MVVM view model directly.

I see a lot of advantages to using the MVVM framework in my UI, it makes control binding so much easier.

My question:

What is the best way to get the data from the controller to the MVVM ViewModel?

I feel that using the MVC ViewModel is duplicating work since I could query my Web API via ajax requests instead rather than translating my MVC ViewModel into my MVVM JS ViewModel.

Would it be a good approach to never return a MVC viewModel to my UI and always use client side Web API calls to retrieve all data?

Thanks,

Nicolas

4

2 回答 2

2

永远不要将 MVC 视图模型返回到我的 UI 并始终使用客户端 Web API 调用来检索所有数据是一种好方法吗?

我会说这取决于您的用例。

您当然可以返回页面在 MVC 模型中显示时需要呈现的数据。请记住,MVC 模型被渲染到服务器上生成的 HTML 页面中。这意味着这些值可以在返回给客户端之前直接注入 HTML。

另请记住,如果您必须多次访问服务器,则可能需要更长的时间才能完全呈现您的页面;一次获取 HTML,然后为每个 Kendo 小部件获取一次异步数据。

也就是说,我通常最终会按照你说的做......只需渲染一个没有模型的 MVC 视图,然后让 Kendo UI 小部件在页面加载后获取它们的数据。

但实际上,这有点取决于您的数据。如果您的 MVC 模型包含:

public string Title { get; set; }

在 Razor 中,你有:

<h1>@Title</h1>

那么这并不是我想要异步重新获取该数据的情况。在这些情况下,我通常会做一些 hacky 的事情,并将值放入页面中:

<script type="text/javascript">
    window.viewData = window.viewData || {};
    window.viewData.Title = "@Title"
</script>

<h1 data-bind="text: Title"></h1>

<script src="viewmodel.js"></script>

然后在 viewmodel.js 文件中(我从返回的 HTML 中创建了一个单独的文件,以便它可以被浏览器缓存)

(function (viewData) {
    var viewModel = kendo.observable({
        Title: viewData.Title
    });

    kendo.bind($("body"), viewModel);
})(window.viewData);

这只是我自己的方法。它不一定适用于所有情况。这一切都取决于您从哪里以及从多少中提取什么数据。

于 2013-10-29T01:28:28.343 回答
0

从我对 MVC 架构的理解来看,MVVM 中的 View Model 和 MVC 中的 ViewModel 是完全不同的。我从您的帖子中可以看出,您正在使用一个框架,借助该框架将数据绑定到视图。您能否详细说明框架或向我们提供代码,以便它可以帮助其他人/我更好地解决您的问题。

于 2013-10-28T18:00:54.897 回答