C# 带列表的Razor表单

C# 带列表的Razor表单,c#,asp.net-mvc,asp.net-mvc-4,razor,C#,Asp.net Mvc,Asp.net Mvc 4,Razor,MVC新手,刚刚从列表中检索表单数据。在我的控制器中,我能够正确地获取我的名称值(配方名称),但无法获取配料名称值,总是返回空值 下面是我的项目中的一些代码片段 模型 公共类配方 { [必需] 公共字符串名称{get;set;} 公共列表成分{get;set;} 公共配方() { 成分=新列表() { 新成分() }; } } 公共类成分 { 公共字符串名称{get;set;} } 看法 使用(Html.BeginForm(“CreateEdit”、“Recipe”)) { @Html.Val

MVC新手,刚刚从列表中检索表单数据。在我的控制器中,我能够正确地获取我的名称值(配方名称),但无法获取配料名称值,总是返回空值

下面是我的项目中的一些代码片段

模型

公共类配方
{
[必需]
公共字符串名称{get;set;}
公共列表成分{get;set;}
公共配方()
{
成分=新列表()
{
新成分()
};
}
}
公共类成分
{
公共字符串名称{get;set;}
}
看法

使用(Html.BeginForm(“CreateEdit”、“Recipe”)) { @Html.ValidationSummary() @LabelFor(x=>x.Name,“Name”) @TextBoxFor(x=>x.Name,新的{@class=“form control”}) @Html.ValidationMessageFor(x=>x.Name) 配料 @LabelFor(x=>x.components.FirstOrDefault().Name,“Name”) @Html.TextBoxFor(x=>x.components.FirstOrDefault().Name,新的{@class=“form control”}) } 控制器

[HttpPost]
public ActionResult CreateEdit(Recipe recipe)
{           
   var recipeName = recipe.Name // <--- Works
   var ingredientName = recipe.Ingredients.FirstOrDefault().Name; //<--- NULL value

   return View(recipe);
}
[HttpPost]
公共操作结果CreateEdit(配方)
{           
var recipeName=recipe.Name//
  • 成分
    配方
    类的属性,属于
    列表
    类型
  • 向其发布CreateEdit的操作有一个参数
    Recipe
  • 要绑定列表对象,我们需要为每个项提供一个索引

    <form method="post" action="/Home/CreateEdit">
    
        <input type="text" name="recipe.Ingredients[0].Name" value="Red Sauce" />
    
        <input type="text" name="recipe.Ingredients[1].Name" value="White Sauce" />    
    
    </form>
    
    
    

    阅读此链接-以便更好地理解此内容。

    请查看此链接:您不能使用
    .FirstOrDefault()
    在视图中-您需要为
    循环使用
    ,或为
    成分使用自定义
    编辑器或模板
    -请参阅。但是如果您只需要一种
    成分
    ,为什么要使用
    列表
    ?@Danieboy感谢您解决了我的问题problem@StephenMuecke这种形式最终将允许添加多种成分对于配方,这是我的下一个挑战:)如果要在视图中动态添加(和删除)集合项,请参阅
    [HttpPost]
    public ActionResult CreateEdit(Recipe recipe)
    {           
       var recipeName = recipe.Name // <--- Works
       var ingredientName = recipe.Ingredients.FirstOrDefault().Name; //<--- NULL value
    
       return View(recipe);
    }
    
    <form method="post" action="/Home/CreateEdit">
    
        <input type="text" name="recipe.Ingredients[0].Name" value="Red Sauce" />
    
        <input type="text" name="recipe.Ingredients[1].Name" value="White Sauce" />    
    
    </form>