1

I am trying to connect asp.net core web api(thats already connected to my local sqlserver and working fine) to my asp.net-mvc5 web app so when the controller is called it fetches the data from database using API

Now, this is how I'm trying to connect the api in my asp.net mvc project, shown below is homeController:

namespace AptitudeTest.Controllers
{

public class HomeController : Controller
{

    string Baseurl = "http://localhost:51448";
    public async Task<ActionResult> Index()
    {
        List<Teacher> teacher = new List<Teacher>();
        //Teacher t1 = new Teacher();
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(Baseurl);
            client.DefaultRequestHeaders.Clear();

            //Define request data format  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
            HttpResponseMessage Res = await client.GetAsync("api/Admin/Get");

            //Checking the response is successful or not which is sent using HttpClient  
            if (Res.IsSuccessStatusCode)
            {
                //Storing the response details recieved from web api   
                var EmpResponse = Res.Content.ReadAsStringAsync().Result;

                //Deserializing the response recieved from web api and storing into the Employee list  
                teacher = JsonConvert.DeserializeObject<List<Teacher>>(EmpResponse);

            }
            //returning the employee list to view  

            return View(teacher);
        }

    }

I expect it to return me teachers as json objects but this is the error im getting: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[AptitudeTest.Teacher]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AptitudeTest.Models.Teacher]'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[AptitudeTest.Teacher]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AptitudeTest.Models.Teacher]'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

1 Answer 1

1

The error you are getting is:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[AptitudeTest.Teacher]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AptitudeTest.Models.Teacher]'.

which means your view expects different model object as input while the passed object is of different type. It looks like that you have in view defined model as:

IEnumerable<Teacher>

while you are returning a List<Teacher>. Either change in view it to List<Teacher> like:

@model List<Teacher>

or return an IEnumerable<Teacher> object from the controller action.

for that you can write the following:

IEnumerable<Teacher> teachers = teacher;
return View(teachers );

Either way you should be able to resolve the error and keep moving.

EDIT:

didn't noticed that there are two different classes in different namespace, one is AptitudeTest.Teacher and other is AptitudeTest.Models.Teacher. the class which we have defined the view should be same which is passed from the action method. Right now there are two classes each in different namespace.

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

5 Comments

I've tried the later one but same error, isnt there some library that can help like axios in react helps to connect my api to my react project(I'm working on same project in reactjs too)
@ShabanaHussain sorry my bad, it looks like you have another issue too, i.e. there are two different classes, one : AptitudeTest.Models.Teacher and second: AptitudeTest.Teacher , both should be same in view and the one passed from action
in view you can set model to the prior one which you are passing from action: @model List<AptitudeTest.Teacher> or pass List<AptitudeTest.Models.Teacher> from action method
Yea thanks, the problem was all about models, now that i have fixed it i have another different error: "could not cast or convert from system.int64 to system.collections.generic.list" referring to code line "teacher = JsonConvert.DeserializeObject<List<Teacher>>(EmpResponse);" now idk what to do with it
inspect in debugger the json response and compare it with your model, most probably the conversion is failing from json to c# object

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.