我正在学习将API与RecipePuppy API结合使用,并尝试将结果显示到网页上。我无法将单个结果显示在列表中以显示它们。
这在控制器中并且可以正常工作:
public string GetData()
{
HttpWebRequest request = WebRequest.CreateHttp("http://www.recipepuppy.com/api/?i=onions,garlic&q=omelet&p=3");
Httpwebresponse response = (Httpwebresponse)request.GetResponse();
StreamReader rd = new StreamReader(response.GetResponseStream());
string ApiText = rd.ReadToEnd();
return ApiText;
}
这就是我遇到的问题。也在控制器中。我只是不确定我是否能正确理解整个JToken。食谱是我创造的模型 用于存储对象。
public List<Recipe> ConvertAPItoRecipes(string APIText)
{
JToken t = JToken.Parse(APIText);
Recipe r = new Recipe();
List<JToken> recipes = t["title"].ToList();
//r.Title = t["title"].ToString();
List<Recipe> r2 = new List<Recipe>();
foreach(JToken x in recipes)
{
Recipe re = new Recipe();
re.Title = x["title"].ToString();
string temp = x["ingredients"].ToString();
List<string> temp2 = temp.Split(',').ToList();
re.Ingredients = temp2;
r2.Add(re);
}
return r2;
}
在控制器中执行操作。我添加了一个对象只是为了查看列表是否正确显示
public IactionResult Index()
{
List<Recipe> recipes = ConvertAPItoRecipes(GetData());
Recipe r = new Recipe();
r.Title = "Steamed Hams";
recipes.Add(r);
ViewBag.num = recipes.Count();
return View(recipes);
}
这是视图。我添加了viewbag.num来列出列表中的项目数,只是为了确认它是空的(它使用我自己添加的“ steam hams”对象读取为1。
@model List<Recipe>
@ViewBag.num
@foreach (var item in Model)
{
<div>
@Html.DisplayFor(modelItem => item.Title)
</div>
}
我希望包含洋葱和大蒜的食谱列表会显示在索引上。似乎可以显示该列表,但是它是空的,我很困惑如何填充它。
非常感谢您的帮助!