6

this is my first question, so I apologize if I mess up the formatting or do this wrong in general, feel free to give me pointers, I'm always open to learn.

Anyway, my issue at hand is that I have a web application I'm working on using ASP.NET 5 and MVC 6, all up to date, and so far for testing, I've been using the localdb and working with fake data. Now, I have a url, with an API token, and login info, and I am using a WebRequest to get the data and stream it with a StreamReader into a variable, writing it, and then trying to return it.

WebRequest req = WebRequest.Create(@"https://url.fortheapi.com/api/search/things?criteria=" + userInput);
req.Method = "GET";
req.Headers["username"] = "user";
req.Headers["password"] = "password";
req.Headers["token"] = "token";

StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

Response.WriteAsync(responseData);

return View(responseData);

Here is where I'm stuck because I am not sure exactly how to pass it to the view as model data, I have no model currently, and I want to make one based on this database and use Entity Framework to work with it like I have been with the localdb. If there's a better way to do it, please feel free to present it. I will accept all the help I can get right now.

2
  • paste your json to json2csharp.com and your model would be approximately like it. Commented Mar 3, 2016 at 20:57
  • so when I make a model from that json, would I just use the same code I have above and on the view page, call that model, and reference the data inside it like I would with a localdb? Commented Mar 3, 2016 at 21:04

2 Answers 2

2

You need to create POCO classes to represent the data you receive from your api call. Once you get the response data, you may simply use a javascript serialize to deserialize the response to an object of your POCO class. You can pass this to your view.

public async Task<ActionResult> Contact()
{
    var req = WebRequest.Create(@"yourApiEndpointUrlHere");    
    var r = await req.GetResponseAsync().ConfigureAwait(false);              

    var responseReader = new StreamReader(r.GetResponseStream());
    var responseData = await responseReader.ReadToEndAsync();

    var d = Newtonsoft.Json.JsonConvert.DeserializeObject<MyData>(responseData);    
    return View(d);
}

Assuming your api returns json data like this

{   "Code": "Test", "Name": "TestName" }

and you have created a POCO class called MyData which can be used to represent the data coming back from the api. You may use json2csharp to generate your C# classes from the json response you received from your api.

public class MyData
{
   public string Code { get; set; }
   public string Name { set;get;}
   //Add other properties as needed
}

Now your view should be strongly typed to this POCO class

@model MyData
<h2>@Model.Code</h2>
<h2>@Model.Name</h2>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your response, I will look into this and try to apply it, I really appreciate your time and effort!
So for the serialization would I have to use this specific type of function or can I use it in a regular IActionResult controller function? I am getting the search criteria from a form and already have all the user data being collected in that function and would like to just plug that data in and get my requested data.
Yes, you can do that in a controller action.
2

If what you are receiving is JSON, you can accomplish this is many ways.

One would be to wrap the code you've posted into a JSON Result typed Action. A very simplistic example below:

    [HttpPost]
    public JsonResult GetIncidentId(int customerId, string incidentNumber)
    {
        JsonResult jsonResult = null;
        Incident incident = null;

        try
        {
            incident = dal.GetIncident(customerId, incidentNumber);
            if (incident != null)
                jsonResult = Json(new { id = incident.Id });
            else
                jsonResult = Json(new { id = -1 });

        }
        catch (Exception exception)
        {
            exception.Log();
        }

        return jsonResult;
    }

Calling it via Javascript from the view and manually populating your form (meh).

Or more elegantly, you could create an MVC model to hold the data you receive and serialise the JSON into that model. An example of which is below:

From: http://www.newtonsoft.com/json/help/html/deserializeobject.htm

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

string json = @"{
  'Email': '[email protected]',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);

Hope this helps and good luck with your app!

10 Comments

If I use the second bit of code you gave me there will I be able to treat it like a "code-first" database model? Will I be able to use get the data normally in the view is what I meant. I'm currently making a model for it and I will test your code, thanks for the response!
Yes, that is correct. You'll be able to use the result as a native View Model. If you find yourself then having to transfer data to a different model, I really like the AutoMapper library which can save syntax. HTH.
actually it would seem that JavaScriptSerializer is not supported in asp.net 5 anymore. The dependency for it has not been updated in years, apparently they're using Newtonsoft.Json now, which is a package I'm looking into for this.
Of course, yes, I had totally forgotten, apologies. I think the asp.net team switched over on mvc4.
Indeed, if your data is an untitled json collection, it's best to have a wrapping class to hold it.
|

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.