这是一种方法。
您有一个单独的 WebAPI 控制器来处理来自客户端的数据访问。
//Inside your CommentsApiController, for example
public IEnumerable<Comment> Get(int id)
{
var comments = _commentsService.Get(int id); //Call lower layers to get the data you need
return comments;
}
您的 MVC 控制器具有返回 PartialViewResults 的操作。这是一个返回局部视图的简单操作。
//Inside your MVC CommentsController, for example
public PartialViewResult CommentsList(int id)
{
return PartialView(id);
}
您的局部视图呈现出您的标记,并带有敲除绑定。我们为我们的 HTML 制作了一个唯一的 ID,因此我们可以将我们的淘汰视图模型绑定到页面的这个特定部分(避免与页面上的其他淘汰组件冲突)。
我们需要的 JavaScript(淘汰视图模型等)被包含在内,创建了一个新的 ViewModel 并应用了淘汰绑定。
@{
var commentsId = Model; //passed from our MVC action
var uniqueIid = System.Guid.NewGuid().ToString();
}
<section class="comments" id="@uniqueIid ">
<ul data-bind="foreach: { data: Comments, as: 'comment' }">
<li>
<span data-bind="text: comment.Author"></span>
<p data-bind="text: comment.Message"></p>
</li>
</ul>
</section>
@Scripts.Render("~/js/comments") //using MVC Bundles to include the required JS
@{
//generate the URL to our WebAPI endpoint.
var url = Url.RouteUrl("DefaultApi", new { httproute = "", controller = "Comments", id = commentsId });
}
<script type="text/javascript">
$(function() {
var commentsRepository = new CommentsRepository('@url');
var commentsViewModel = new CommentsViewModel(commentsRepository);
var commentsElement = $('#@uniqueIid')[0];
ko.applyBindings(commentsViewModel, commentsElement);
});
</script>
在我们的 JavaScript 中,我们定义了淘汰视图模型等。
var CommentsRepository = function(url) {
var self = this;
self.url = url;
self.Get = function(callback) {
$.get(url).done(function(comments) {
callback(comments);
});
};
};
var CommentsViewModel = function (commentsRepository) {
var self = this;
self.CommentsRepository = commentsRepository;
self.Comments = ko.observableArray([]);
//self executing function to Get things started
self.init = (function() {
self.CommentsRepository.Get(function(comments) {
self.Comments(comments);
});
})();
};
我们完成了!要使用这个新组件,我们可以使用RenderAction
@* inside our Layout or another View *@
<article>
<h1>@article.Name</h1>
<p>main page content here blah blah blah</p>
<p>this content is so interesting I bet people are gonna wanna comment about it</p>
</article>
@Html.RenderAction("Comments", "CommentsList", new { id = article.id })