如何在MVC的部分视图中返回json?

Obs*_*vus 6 c# asp.net-mvc json jsonresult asp.net-mvc-3

我有以下代码:

[HttpPost]
public JsonResult Index2(FormCollection fc)
{
    var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
    return Json(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)));
}
Run Code Online (Sandbox Code Playgroud)

但我想在部分视图中使用它,我该怎么做?

ILy*_*Lya 2

如果我正确理解您的需求,您可以尝试以下操作

public JsonResult Index2(FormCollection fc)
{
    var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
    return Json(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)), "text/html", JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

设置 c 内容类型很重要,因为如果您使用 调用此操作,JsonResult 将覆盖整个响应的内容类型Html.RenderAction。这不是一个好的解决方案,但在某些情况下有效。

相反,您也可以尝试更好的解决方案:

var scriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonString = scriptSerializer.Serialize(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)));
Run Code Online (Sandbox Code Playgroud)

然后你可以用字符串表示来做你想做的一切。这就是JsonResult它内部实际所做的事情。顺便说一句,您可以在此处使用任何 json 序列化程序,获得同样的成功。

如果你想在客户端访问它。您不需要更改您的代码。如果使用 jQuery:

$.post('<%= Url.Action("Index2") %>', { /* your data */ }, function(json) { /* actions with json */ }, 'json')
Run Code Online (Sandbox Code Playgroud)

如果你想将它传递给你的视图模型,那么:

[HttpPost]
public ActionResult Index2(FormCollection fc)
{
    var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
    return PartialView(new MyModel { Data = goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)) });
}
Run Code Online (Sandbox Code Playgroud)