Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call web api in controller and return into view MVC4

I have a project using MVC4, i want to ask how to get data from webapi and return into view.

Model

public class Name
{
    public Int32 NameId { get; set; }
    public String FirstName{ get; set; }
    public String LastName{ get; set; }
    public String CreatedBy { get; set; }
}

public class IListMyProject
{
    public List<Name> Names { get; set; }
}

I can list all in my Index.cshtml using this code

public ActionResult Index()
    {
        string securityToken = repo.GetTokens();
        if (securityToken != null)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "webapiurl/api/Name/Get?$orderby=LastName&$top=10");
            string authHeader = System.Net.HttpRequestHeader.Authorization.ToString();
            httpRequestMessage.Headers.Add(authHeader, string.Format("JWT {0}", securityToken));
            var response = client.SendAsync(httpRequestMessage)
                .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode())
                .Result;
            if (response.IsSuccessStatusCode)
            {
                model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList();

            }
        }
        return View("Index", model);
    }

i can return my view. and now i have another view called Details.cshtml with this code :

 public ActionResult Details(string id)
    {
        string securityToken = repo.GetTokens();
        if (securityToken != null)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "webapiurl/api/Name/GetById/"+id+"");
            string authHeader = System.Net.HttpRequestHeader.Authorization.ToString();
            httpRequestMessage.Headers.Add(authHeader, string.Format("JWT {0}", securityToken));

            var response = client.SendAsync(httpRequestMessage)
                .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode())
                .Result;
            if (response.IsSuccessStatusCode)
            {

                model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList();

            }
        }
        return View(model);
    }

For this Detail, my Json looks like this:

 application/json, text/json
 {
  "NameId": 1,
  "FirstName": "This is First Name",
  "LastName": "This is Last Name",
  "CreatedBy": "This is Created By"
 }

when i run it, i get this error :

 Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1[Models.Name]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

 To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

 Path 'NameId', line 1, position 10.

How do i fix this, im new to webapi. i wonder why do if i list all (for index, i use api/get) it works, but when i want to show it in detail, it doesn't work.

thank for help

Regards

EDIT

when i debug in

 model.Names = response.Content.ReadAsAsync<IList<Name>>().Result.ToList();

its says Null, is there something wrong when i try to get the response ?

like image 979
ntep vodka Avatar asked Feb 09 '13 04:02

ntep vodka


People also ask

Can an API controller return a view?

You don't return a View from an API controller. But you can return API data from an MVC controller. The solution would be to correct the errors, not try to hack the API controller.

Can we call Web API from MVC controller?

First of all, create MVC controller class called StudentController in the Controllers folder as shown below. Right click on the Controllers folder > Add.. > select Controller.. Step 2: We need to access Web API in the Index() action method using HttpClient as shown below.

Can we use View in Web API?

MVC stands for Model View Controller. It is used to create a web application that returns both data and view (HTML). Web API is an open-source platform and framework used to create HTTP-based services that only return data and not view.


1 Answers

The issue is that:

{
  "NameId": 1,
  "FirstName": "This is First Name",
  "LastName": "This is Last Name",
  "CreatedBy": "This is Created By"
}

can't be deserialized as an IList. The JSON you have above is just one name, not a collection of Names. So Json.NET deserialization will fail.

Make sure that your Web API controller returns an IList, or change your MVC code to read the content as a single Name. A collection of names in JSON would look like this instead:

[{
  "NameId": 1,
  "FirstName": "This is First Name",
  "LastName": "This is Last Name",
  "CreatedBy": "This is Created By"
},
{
  "NameId": 2,
  "FirstName": "This is First Name",
  "LastName": "This is Last Name",
  "CreatedBy": "This is Created By"
}]
like image 97
Youssef Moussaoui Avatar answered Sep 22 '22 03:09

Youssef Moussaoui