gpt4 book ai didi

c# - 带列表的 Razor 表单

转载 作者:太空宇宙 更新时间:2023-11-03 15:12:09 25 4
gpt4 key购买 nike

MVC 的新手,只是在努力从 List<> 中检索我的表单数据。在我的 Controller 中,我能够正确获取我的名称值(配方名称)但无法获取成分名称值,总是返回 NULL?

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

型号

public class Recipe
{

[Required]
public string Name { get; set; }
public List<Ingredient> Ingredients { get; set; }

public Recipe()
{
Ingredients = new List<Ingredient>()
{
new Ingredient()
};

}
}

public class Ingredient
{
public string Name { get; set; }
}

查看

@using (Html.BeginForm("CreateEdit", "Recipe"))
{
@Html.ValidationSummary()
<div class="form-group">
@Html.LabelFor(x => x.Name, "Name")
@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Name)
</div>

<h2>Ingredient(s)</h2>
<div class="form-group">
@Html.LabelFor(x => x.Ingredients.FirstOrDefault().Name, "Name")
@Html.TextBoxFor(x => x.Ingredients.FirstOrDefault().Name, new { @class = "form-control" })
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" text="submit" />
</div>
}

Controller

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

return View(recipe);
}

最佳答案

  1. Ingredients是类 Recipe 的属性类型为 List<Ingredient> .
  2. 您要向其发送 CreateEdit 的操作有一个参数 Recipe .

要绑定(bind)列表对象,我们需要为每个项目提供一个索引。比如

<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>

阅读此链接 - http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/更好地理解这一点。

关于c# - 带列表的 Razor 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40703690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com