当我运行程序并在控制器方法中设置断点时,我可以单步执行并查看recipe.Name和recipe.ID已正确填充,但recipe.Ingredients为空。
我在俯瞰什么?这是我的相关代码:
型号:
public class Recipe
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Ingredient> Ingredients { get; set; }
}
查看:
@model Cookbook.Models.Recipe
// removed irrelevant code for this question
<dt>@Html.DisplayNameFor(model => model.Name)</dt>
<dd>@Html.DisplayFor(model => model.Name)</dd>
<dd>
<table class="table">
<tr><th>Ingredient</th></tr>
@foreach (var item in Model.Ingredients)
{
<tr><td>@Html.DisplayFor(model => item.Name)</td></tr>
}
</table>
</dd>
<p> @Html.ActionLink("Export Data", "ExportData", Model)</p>
控制器:
public ActionResult ExportData (Recipe recipe)
{
//I am dynamically building an XML file by constructing it line by line
string xml = recipe.Name + "\r\n\r\n"; //Here, Name is populated
//Here, recipe.Ingredients is empty even though it appears in the view
foreach(Ingredient ing in recipe.Ingredients)
{
xml = xml + ing.Ingredient.Name + "\r\n";
}
}
答案 0 :(得分:1)
您不能使用@Html.ActionLink()
将包含属性集合(或复杂对象)的模型传递给get方法。在内部,该方法通过在模型中的每个属性上调用.ToString()
方法来生成查询字符串值。在你的情况下它正在生成
...?ID=someValue&Name=someValue&Ingredients=System.Collections.Generic.ICollection<Ingredient>
为了绑定你的模型,它需要
...?....&Ingredients[0].Name=someValue&Ingredients[1].Name=someValue&...
相反。将模型的ID传递给方法,然后再次获取模型(就像在生成此视图的GET方法中所做的那样)来构建xml文件
@Html.ActionLink("Export Data", "ExportData", new { id = Model.ID })
public ActionResult ExportData (int ID)
{
var recipe = db.Recipies.Where(r => r.ID = ID).FirstOrDefault();
....
}