如何从剃刀中的表单获取对象列表?

时间:2019-08-22 23:35:21

标签: c# asp.net razor

我需要从用户那里接收项目列表。具体来说,我有一些配方(餐厅菜单项),上面列出了食材清单。我需要一个页面,用户可以在其中为每种配方添加任意数量的配料。我需要将每种配方的食材清单返回到后端。

我已经搜索了几个小时,但是找不到适合我的解决方案。我认为我需要对Html.BeginCollectionItem做一些事情,但是我不太了解它是如何工作的,甚至无法安装它。另外,我一直在尝试使用局部函数,但无济于事。

newRecipes.cshtml

@model AddRecipesView

@foreach(Recipe recipe in Model.Recipes){
    Display each recipe here as well as a dropdown(or list of
    dropdowns) for the user to add as many ingredients to the recipe
    as they like"
}

AddRecipesView.cs

public class AddRecipesView{
    public Merchant Merchant{get;set;}

    public List<Recipe> Recipes{get;set;}
}

Merchant.cs

public class Merchant{
    public string id{get;set;}
    public string Name{get;set;}
    public string LastCheckedTime{get;set;}

    public List<Pantry> PantryItems{get;set;}

    public List<Recipe> Recipes{get;set;}
}

Recipe.cs

public class Recipe{
    public string id{get;set;}
    public string name{get;set;}

    public string MerchantId{get;set;}
    public Merchant Merchant{get;set;}

    public List<RecipeComponent> RecipeComponents{get;set;}
}

控制器

[HttpGet("recipes/new")]
public IActionResult NewRecipes(){
    AddRecipesView viewModel = CreateAddRecipesView();          

    return View("newRecipes", viewModel);
}

public AddRecipesView CreateAddRecipesView(){
        AddRecipesView viewModel = new AddRecipesView();

        viewModel.Merchant = context.Merchants
            .Include(m => m.PantryItems)
            .ThenInclude(pi => pi.Ingredient)
            .FirstOrDefault(m => m.id == merchantId);

        string json = new WebClient().DownloadString($"https://apisandbox.dev.clover.com/v3/merchants/{merchantId}/items?access_token={token}");
        Items items = JsonConvert.DeserializeObject<Items>(json);
        foreach(ItemElement item in items.elements){
            Recipe recipe = context.Recipes.FirstOrDefault(r => r.id == item.id);
            viewModel.Recipes.Append(recipe);
        }

        return viewModel;
    }

我需要从用户那里获取每种食谱的原料清单。我只是不确定如何使用cshtml做到这一点。

0 个答案:

没有答案