2012-05-28 6 views
6

tôi có mã này như sau:Làm thế nào tôi có thể trả về json trên một phần xem trong MVC?

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

Nhưng tôi muốn sử dụng nó trên một PartialView thay vào đó, làm thế nào tôi có thể làm điều đó?

+1

bạn có muốn gọi từ chế độ xem một phần qua mã javascript không? –

Trả lời

2

Nếu tôi hiểu đúng những gì bạn cần, bạn có thể thử cách sau

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

Điều quan trọng là để thiết lập c kiểu nội dung vì JsonResult sẽ ghi đè kiểu nội dung của toàn bộ phản ứng nếu bạn gọi hành động này sử dụng Html.RenderAction. Nó không phải là một giải pháp tốt nhưng nó hoạt động trong một số trường hợp.

Thay vào đó bạn cũng có thể thử giải pháp tốt hơn:

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

Sau đó, bạn có thể làm tất cả mọi thứ bạn muốn với một chuỗi đại diện. Đó là những gì thực sự JsonResult làm bên trong của nó. Btw, với cùng một thành công, bạn có thể sử dụng bất kỳ serializer json ở đây.

Nếu bạn muốn truy cập nó trên máy khách. Bạn không cần phải thay đổi mã của mình. Trong trường hợp sử dụng jQuery:

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

Nếu bạn muốn vượt qua nó để mô hình điểm của bạn sau đó:

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

Bạn cũng có thể trả về một Xem phần Thay vì Json.

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