mvc return json and view get json code example
Example 1: how to return json data from mvc controller to view
When you do return Json(...) you are specifically telling MVC not to use a view, and to serve serialized JSON data. Your browser opens a download dialog because it doesn't know what to do with this data.
If you instead want to return a view, just do return View(...) like you normally would:
var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return View(new { Values = listLocation });
Then in your view, simply encode your data as JSON and assign it to a JavaScript variable:
<script>
var values = @Html.Raw(Json.Encode(Model.Values));
</script>
Example 2: can a Json Action return a view?
protected string RenderPartialViewToString(string viewName, object model)
{
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}