0

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>
7
  • Why would you pass a string and not a model? Commented Sep 7, 2016 at 6:33
  • Because I want json on the client as a data source for a jquery grid widget. Also, this data is coming from a 3rd party api call so it's already a string. I just need to pipe it to the view. I will try what the others suggest and see if it works. thanks Commented Sep 7, 2016 at 6:47
  • 1
    The parse the string to an object and pass the model to the view (or parse it in the client using JSON.parse()) Commented Sep 7, 2016 at 6:54
  • Why should I go to the trouble of creating a model and deserializing this perfectly valid string of json when it's what I need on the client anyway? Commented Sep 7, 2016 at 7:08
  • You have to de-serialize/parse it somewhere - a string on its own is no use to you :) Commented Sep 7, 2016 at 7:11

4 Answers 4

1

Change controller code to :

public async Task<JsonResult> Index()
{
  string data = await _myService.GetList();
  return Json(new
        {
            JsonData = data ,
            Status = true
        }, JsonRequestBehavior.AllowGet);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change controller code to :

public async Task<JsonResult> Index()
{
    string data = await _myService.GetList();
    return Json(data, JsonRequestBehavior.AllowGet); 
}

Comments

0

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>

Comments

0

This one works too. Model as a string object

<script>
   var data = @Html.Raw(Model)
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.