簡體   English   中英

如何在MVC的部分視圖中返回json?

[英]How can I return json on a partialview in MVC?

我有以下代碼:

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

但我想在部分視圖中使用它,我該怎么做?

如果我正確理解您的需求,您可以嘗試以下方法

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

設置c內容類型很重要,因為如果使用Html.RenderAction調用此操作,JsonResult將覆蓋整個響應的內容類型。 這不是一個好的解決方案,但它在某些情況下有效。

相反,您也可以嘗試更好的解決方案

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

然后,您可以使用字符串表示執行所需的一切。 這實際上JsonResultJsonResult所做的事情。 順便說一句,同樣的成功你可以在這里使用任何json序列化器。

如果您想在客戶端訪問它。 您無需更改代碼。 在使用jQuery的情況下:

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

如果要將其傳遞給視圖模型,則:

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

您還可以返回部分View而不是Json。

[HttpPost]
public ActionResult Index2(FormCollection fc)
{
   var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
   return PartialView(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM