0

I tried many things but I'm still unable to display data in View. I'm only getting a null result in View page. When I debug using a break point, I can clearly see data in the variables but can't return it in View. Seems like I need a List...
The aim is to return json data in a HTML View.

        public async Task<ActionResult> GetAPIStringAsync(Students model)
        {

            HttpClient client = new HttpClient();

            string APIdatas = null;

            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/");
            if (response.IsSuccessStatusCode)
            {
                APIdatas = await response.Content.ReadAsStringAsync();
            }


            var stringJson = JsonConvert.DeserializeObject<IEnumerable<Students>>(APIdatas);

            return Json(model, JsonRequestBehavior.AllowGet);
            return View();

        }


public class Students
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Url { get; set; }
}

and in my View, I have this :

@model IEnumerable<AutoMobile.Web.Models.Manage.Students>

@foreach (var item in Model.OrderBy(x => x.Id))
{

<td>
    @Html.DisplayFor(modelItem => item.Id)
</td>
<td>
    @Html.DisplayFor(modelItem => item.Title)
</td>
<td>
    @Html.DisplayFor(modelItem => item.Url)
</td>


}
4
  • why are you returning json? Commented Oct 15, 2019 at 10:17
  • You need to return View(model); Commented Oct 15, 2019 at 10:19
  • I'm fetching json list thru webapi. Commented Oct 15, 2019 at 10:19
  • then you can use ajax call to bind data in view Commented Oct 15, 2019 at 10:20

1 Answer 1

3

First prepare the json data. Then map this data to C# class

So first Create C# class which will hold the Json Data

public class RootObject
{
    public int userId { get; set; }
    public int id { get; set; }
    public string title { get; set; }
    public bool completed { get; set; }
}

Once C# class is created, you can fetch the json and deserialize it to C# class Then You have to return this model to view.

public ActionResult GetJsonDataModel()
    {
        var webClient = new WebClient();
        webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
        var json = webClient.DownloadString(@"https://jsonplaceholder.typicode.com/todos/1");
        Models.JsonModel.RootObject objJson = JsonConvert.DeserializeObject<Models.JsonModel.RootObject>(json); //here we will map the Json to C# class
        //here we will return this model to view
        return View(objJson);  //you have to pass model to view
    }

Now in View you have to write below code:

@model ProjectDemoJsonURL.Models.JsonModel.RootObject
@{
    ViewBag.Title = "GetJsonDataModel";
    Layout = "~/Views/Shared/_Layout.cshtml";
 }
<h2>GetJsonDataModel</h2>
@{ 
   <table>
    <tr>
        <th>userId</th>
        <th>id</th>
        <th>title</th>
        <th>completed</th>
    </tr>
    <tr>
        <th>@Model.userId</th>
        <th>@Model.id</th>
        <th>@Model.title</th>
        <th>@Model.completed</th>
    </tr>
</table>
}

Please check below link: in below blog, Json data is fetched from URL in controller method, then json is deserialized to a model class, then this model is returned to a view, and data is displayed in view

https://fullstackdotnetcoder.blogspot.com/p/how-to-read-parse-json-data-from-url-in.html

I hope it helps.

Sign up to request clarification or add additional context in comments.

6 Comments

I'm testing it and getting an error saying : Error CS0234 The type or namespace name 'JsonModel' does not exist in the namespace '....Models' (are you missing an assembly reference?)
You have to create folder in Model-> JsonModel. Please refer blog in detail so that you can get an idea. Or open your C# class which you are using to map your json. Copy that class's namespace. In my case it was: ProjectDemoJsonURL.Models.JsonModel.RootObject [ Here it is SolutionName->ModelsFolder->JsonModelFolder-> RootObject Class. So this way you can find your namespace of your C# class ]
@ Amar Gadekar. It's almost working but I need to retrieve a List of data, not only one. what if you want to return the whole List from; (jsonplaceholder.typicode.com/todos) and display it in a View. How do I do it? I need the whole data in a List so that I handle handle it manually.
use foreach(var itm in Model) then iterate through model
when I try to run the project to fetch a list of data from (jsonplaceholder.typicode.com/todos)) I'm getting an error ({"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '.Models.Manage.RootObject' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\n ). it's only work when you fetch one data (jsonplaceholder.typicode.com/todos/1)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.