0
votes

Background: I have this school project where I want to make a recipe web app using https://developer.edamam.com/edamam-docs-recipe-api.

What I've done so far:

  1. Made a get request in Postman and took the JSON data and generated C# with json2csharp.com
namespace EdamaAPI.Models
{
    public class Rootobject
    {
        public string q { get; set; }
        public int from { get; set; }
        public int to { get; set; }
        public Params _params { get; set; }
        public bool more { get; set; }
        public int count { get; set; }
        public Hit[] hits { get; set; }
    }

    public class Params
    {
        public object[] sane { get; set; }
        public string[] q { get; set; }
        public string[] app_key { get; set; }
        public string[] health { get; set; }
        public string[] from { get; set; }
        public string[] to { get; set; }
        public string[] calories { get; set; }
        public string[] app_id { get; set; }
    }

    public class Hit
    {
        public Recipe recipe { get; set; }
        public bool bookmarked { get; set; }
        public bool bought { get; set; }
    }

    public class Recipe
    {
        public string uri { get; set; }
        public string label { get; set; }
        public string image { get; set; }
        public string source { get; set; }
        public string url { get; set; }
        public string shareAs { get; set; }
        public float yield { get; set; }
        public string[] dietLabels { get; set; }
        public string[] healthLabels { get; set; }
        public object[] cautions { get; set; }
        public string[] ingredientLines { get; set; }
        public Ingredient[] ingredients { get; set; }
        public float calories { get; set; }
        public float totalWeight { get; set; }
        public Totalnutrients totalNutrients { get; set; }
        public Totaldaily totalDaily { get; set; }
        public Digest[] digest { get; set; }
    }

    public class Totalnutrients
    {
        public ENERC_KCAL ENERC_KCAL { get; set; }
        public FAT FAT { get; set; }
        public FASAT FASAT { get; set; }
        public FATRN FATRN { get; set; }
        public FAMS FAMS { get; set; }
        public FAPU FAPU { get; set; }
        public CHOCDF CHOCDF { get; set; }
        public SUGAR SUGAR { get; set; }
        public PROCNT PROCNT { get; set; }
        public CHOLE CHOLE { get; set; }
        public NA NA { get; set; }
        public CA CA { get; set; }
        public MG MG { get; set; }
        public K K { get; set; }
        public FE FE { get; set; }
        public ZN ZN { get; set; }
        public P P { get; set; }
        public VITA_RAE VITA_RAE { get; set; }
        public VITC VITC { get; set; }
        public THIA THIA { get; set; }
        public RIBF RIBF { get; set; }
        public NIA NIA { get; set; }
        public VITB6A VITB6A { get; set; }
        public FOLDFE FOLDFE { get; set; }
        public FOLFD FOLFD { get; set; }
        public VITB12 VITB12 { get; set; }
        public VITD VITD { get; set; }
        public TOCPHA TOCPHA { get; set; }
        public VITK1 VITK1 { get; set; }
        public FIBTG FIBTG { get; set; }
    }

    public class ENERC_KCAL
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FAT
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FASAT
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FATRN
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FAMS
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FAPU
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class CHOCDF
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class SUGAR
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class PROCNT
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class CHOLE
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class NA
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class CA
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class MG
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class K
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FE
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class ZN
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class P
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITA_RAE
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITC
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class THIA
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class RIBF
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class NIA
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITB6A
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FOLDFE
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FOLFD
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITB12
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITD
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class TOCPHA
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITK1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FIBTG
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class Totaldaily
    {
        public ENERC_KCAL1 ENERC_KCAL { get; set; }
        public FAT1 FAT { get; set; }
        public FASAT1 FASAT { get; set; }
        public CHOCDF1 CHOCDF { get; set; }
        public PROCNT1 PROCNT { get; set; }
        public CHOLE1 CHOLE { get; set; }
        public NA1 NA { get; set; }
        public CA1 CA { get; set; }
        public MG1 MG { get; set; }
        public K1 K { get; set; }
        public FE1 FE { get; set; }
        public ZN1 ZN { get; set; }
        public P1 P { get; set; }
        public VITA_RAE1 VITA_RAE { get; set; }
        public VITC1 VITC { get; set; }
        public THIA1 THIA { get; set; }
        public RIBF1 RIBF { get; set; }
        public NIA1 NIA { get; set; }
        public VITB6A1 VITB6A { get; set; }
        public FOLDFE1 FOLDFE { get; set; }
        public VITB121 VITB12 { get; set; }
        public VITD1 VITD { get; set; }
        public TOCPHA1 TOCPHA { get; set; }
        public VITK11 VITK1 { get; set; }
        public FIBTG1 FIBTG { get; set; }
    }

    public class ENERC_KCAL1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FAT1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FASAT1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class CHOCDF1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class PROCNT1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class CHOLE1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class NA1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class CA1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class MG1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class K1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FE1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class ZN1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class P1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITA_RAE1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITC1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class THIA1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class RIBF1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class NIA1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITB6A1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FOLDFE1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITB121
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITD1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class TOCPHA1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class VITK11
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class FIBTG1
    {
        public string label { get; set; }
        public float quantity { get; set; }
        public string unit { get; set; }
    }

    public class Ingredient
    {
        public string text { get; set; }
        public float weight { get; set; }
    }

    public class Digest
    {
        public string label { get; set; }
        public string tag { get; set; }
        public string schemaOrgTag { get; set; }
        public float total { get; set; }
        public bool hasRDI { get; set; }
        public float daily { get; set; }
        public string unit { get; set; }
        public Sub[] sub { get; set; }
    }

    public class Sub
    {
        public string label { get; set; }
        public string tag { get; set; }
        public string schemaOrgTag { get; set; }
        public float total { get; set; }
        public bool hasRDI { get; set; }
        public float daily { get; set; }
        public string unit { get; set; }
    }

}
  1. Sending an get request to access the data and deserialize it.
public class RecipeController : Controller
{           
    public async Task<ActionResult> Index()
    {
        List<Recipe> RecInfo = new List<Recipe>();

        using (var client = new HttpClient())
        {
            //Passing service base url  
            client.BaseAddress = new Uri("https://api.edamam.com");

            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.edamam.com/search?q=chicken&app_id=a88093f8&app_key=4513de36c431f9936462ef4391f631e4&from=0&to=3&calories=gte%20591,%20lte%20722&health=alcohol-free");

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

                //Deserializing the response recieved from web api and storing into the Employee list  
                RecInfo = JsonConvert.DeserializeObject<List<Recipe>>(name); 
            }

            //returning the employee list to view  
            return View(RecInfo);
        }
    }
}
  1. Autogenerated View with Visual studio.
@model IEnumerable<EdamaAPI.Models.Recipe>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.uri)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.label)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.image)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.source)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.url)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.shareAs)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.yield)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.calories)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.totalWeight)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.uri)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.label)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.image)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.source)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.url)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.shareAs)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.yield)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.calories)
        </td>
        <td>
           @Html.DisplayFor(modelItem => item.totalWeight)
       </td>
       <td>
           @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
           @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
           @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */               })
       </td>
   </tr>
}  
</table>

When I try to run the project this error occurs:

The model item passed into the dictionary is of type 'EdamaAPI.Models.Recipe', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[EdamaAPI.Models.Ingredient]'.

Stack Trace:

[InvalidOperationException: The model item passed into the dictionary is of type 'EdamaAPI.Models.Recipe', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[EdamaAPI.Models.Ingredient]'.]
   System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +175
   System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +107
   System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +49
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +99
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.c__DisplayClass2b.b__1c() +173
   System.Web.Mvc.Async.c__DisplayClass21.b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129 

I've been searching for hours on Google without luck and I could really use a guiding hand right now! If there is any information that I forgot to include, tell me and I'll get that sorted out right away.

1
Where does it throw that exception? The stack trace would be helpfulfredrik
@less no it is a sequence, just badly named.Aluan Haddad
All those classes with the same properties :O.... Please use something like an enum to define the type as an additional property and have only 1 class instead of ~20.Mixxiphoid
We might be missing something here... Like, you are being redirected to an unexpected view..? Where is the view you are displaying located in the project? Search your project for "@model IEnumerable<EdamaAPI.Models.Ingredient>" in cshtml files.Tewr
Where exactly did you get this exception?inthevortex

1 Answers

0
votes

The exception says it all:

Look at the exception

The model item passed into the dictionary is of type 'EdamaAPI.Models.Recipe', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[EdamaAPI.Models.Ingredient]'.

Look at the model:

@model IEnumerable<EdamaAPI.Models.Recipe>

You pass a recipe model to the view while the view required ingredient model.

This will work:

public class RecipeController : Controller
    {

        public async Task<ActionResult> Index()
        {
            List<Ingredient> RecInfo = new List<Ingredient>();

            using (var client = new HttpClient())
            {
                //Passing service base url  
                client.BaseAddress = new Uri("https://api.edamam.com");

                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.edamam.com/search?q=chicken&app_id=a88093f8&app_key=4513de36c431f9936462ef4391f631e4&from=0&to=3&calories=gte%20591,%20lte%20722&health=alcohol-free");

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

                    //Deserializing the response recieved from web api and storing into the Employee list  
                    RecInfo = JsonConvert.DeserializeObject<List<Ingredient>>(name);

                }
                //returning the employee list to view  
                return View(RecInfo);
            }
        }
}

but that's not what you need, as you need recipe model. Change your action to accept a generic Recipe list.