How can I return json on partial view in MVC?

I have the 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 in partial view instead, how can I do this?

+6
source share
2 answers

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") %>', { /* your data */ }, function(json) { /* actions with 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)) }); } 
+2
source

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))); } 
0
source

Source: https://habr.com/ru/post/916827/


All Articles