I'm new to ASP.NET MVC. After user authentication in my app I am redirecting to a controller/action
. In that action I am getting some json data from a service.
I would like to pass that string data to a view and then manipulate the json with javascript. Note:I am talking about a string, not a model. In Webforms,
I would typically have a page-scoped string variable like: string _json
. Then I would set that var to the json returned by my service. And then in my markup page I would have:
<script>
var data = <%_json%>;
etc..
</script>
Is there a way to do this in ASP.NET MVC?:
Controller
public async Task<ActionResult> Index()
{
string data = await _myService.GetList();
return View(model); //here I want my view to know about data
}
View
<script>
var json = @data //something like this?
</script>
4 Answers 4
Change controller code to :
public async Task<JsonResult> Index()
{
string data = await _myService.GetList();
return Json(new
{
JsonData = data ,
Status = true
}, JsonRequestBehavior.AllowGet);
}
Change controller code to :
public async Task<JsonResult> Index()
{
string data = await _myService.GetList();
return Json(data, JsonRequestBehavior.AllowGet);
}
If your GetList
method returns a correct json string then simply use ViewBag
:
Controller
public async Task<ActionResult> Index()
{
ViewBag.SomeData = await _myService.GetList();
return View();
}
View
<script>
var json = @ViewBag.SomeData ;
</script>
In other case you should implement another method which will result in correct json string, for example @Sarang version will return the correct string. Usage of it:
<script>
var json = @Html.Action("YourMethod", "YourController") ;
</script>
This one works too. Model as a string object
<script>
var data = @Html.Raw(Model)
</script>
JSON.parse())
string
on its own is no use to you :)