How can I return json on a partialview in MVC?
Asked Answered
S

2

6

I have this following code:

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

But I want to use it on a partialview instead , how can I do that?

Schematism answered 28/5, 2012 at 9:23 Comment(1)
do you want to call it from a partial view via javascript code?Enteritis
C
2

If i correctly understand what you need, you may try the following

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

It's important to set c content type because JsonResult will override content type of whole response if you call this action using Html.RenderAction. It's not a good solution but it works in some cases.

Instead you can also try better solution:

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

Then you can do everything you want with a string representation. It is what actually JsonResult do inside of it. Btw, with the same success you can use any json serializer here.

If you want to access it on client. You don't need to change your code. In case of using jQuery:

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

If you want to pass it to your view model then:

[HttpPost]
public ActionResult Index2(FormCollection fc)
{
    var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
    return PartialView(new MyModel { Data = goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)) });
}
Cardiganshire answered 28/5, 2012 at 10:35 Comment(0)
F
0

You can also return a partial View Instead of Json.

[HttpPost]
public ActionResult Index2(FormCollection fc)
{
   var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate();
   return PartialView(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)));
}
Fiddlewood answered 28/5, 2012 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.