If I understand correctly what you need, you can 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 is important to set the content type to c because JsonResult will override the content type of the whole response if you invoke this action using Html.RenderAction
. This is not a good solution, but it works in some cases.
Instead, you can also try a better solution:
var scriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var jsonString = scriptSerializer.Serialize(goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)));
Then you can do whatever you want with a string representation. This is what JsonResult
actually does inside. Btw, with the same success you can use any json serializer here.
If you want to access it on the client. You do not need to change your code. In case of using jQuery:
$.post('<%= Url.Action("Index2") %>', { }, function(json) { }, 'json')
If you want to pass it to your view model, follow these steps:
[HttpPost] public ActionResult Index2(FormCollection fc) { var goalcardWithPlannedDate = repository.GetUserGoalCardWithPlannedDate(); return PartialView(new MyModel { Data = goalcardWithPlannedDate.Select(x => new GoalCardViewModel(x)) }); }
source share