我想将 ViewModel 从控制器发送到 JSON 格式的视图。
控制器:
public ActionResult Select(int pageLimiter)
{
var viewModel = new ArticlesViewModel
{
Articles = this.Service.GetArticles(0, 0, 0),
ArticlesTotal = this.Service.CountArticles(0),
Pages = new List<string>
{
"1", "2", "3"
}
};
return Json(viewModel, JsonRequestBehavior.AllowGet);
}
看法:
<ul class="articleList">
@if (@Model != null)
{
foreach (var article in @Model.Articles)
{
<li>
<header><a href="/Article/@article.ArticleId">@article.Title</a></header>
<nav>
<span>@article.AuthorName</span> |
<time>@article.PublishDate.ToString("")</time> |
<span><a href="/Articles/@article.CategoryId">@article.CategoryName</a></span> |
<span>@article.Comments Comments</span>
</nav>
<section>
@article.Content
</section>
</li>
}
}
</ul>
<script type="text/javascript">
$(document).ready(function () {
GetArticles(5);
$("#selectPager").change(function () {
var selectedItem = "";
$("#selectPager option:selected").each(function () {
selectedItem = $(this).text();
});
GetArticles(selectedItem);
});
});
function GetArticles(pageLimitValue) {
$.ajax(
{
url: "/Articles/Select",
dataType: "json",
data: { pageLimiter: pageLimitValue },
async: true,
beforeSend: function () {
alert("before");
},
complete: function (data) {
@Model = SOME_MAGIC_TRICKS
}
});
}
正如你所看到的,在完整的事件中是 SOME_MAGIC_TRICKS。在这个地方我想设置从控制器获得的@Model。有可能吗?如何将 ajax 结果中的数据插入视图模型(默认为空)?