ASP.NET MVC @ Html.EditorFor(model => model.property)但是

时间:2012-02-02 02:38:02

标签: c# asp.net-mvc-3 collections model

如果我有导航属性怎么办?我在我正在尝试编辑的模型中有另一个模型的集合。我想显示collection属性中每个对象的复选框列表。到目前为止,这是我试过的......

@{

            foreach (var category in ViewBag.Categories)
            {
                if (Model.Categories.Contains(category))
                {
                    <input type="checkbox" name="selected-categories" value="category.CategoryId" checked="checked" />@category.Name
                }
                else
                {
                    <input type="checkbox" name="selected-categories" value="@category.CategoryId" />@category.Name
                }
            }   
         }

但它因EntityCommandExecutionException而失败。在我的if语句中,我如何访问model.Categories,就像我在@Html.EditorFor(model => model.Id) ???

1 个答案:

答案 0 :(得分:0)

使用强类型视图是我的方式。创建一个包含模型的ViewModel,并将此ViewModel用于强类型视图。

域模型和ViewModel(简化)

public class YourModel
{
    string Category { get ; set ; }
}

public class YourViewModel
{
    public List<string> PossibleCategories { get ; set ; }
    public YourModel YourData { get ; set ; }
}

然后是视图:

@model YourViewModel


@{ 
    foreach (string CurrCategory in Model.PossibleCategories) 
    { 
        if (Model.YourData.Category == CurrCategory)
        { 
            @Html.CheckBox(CurrCategory, new { @checked = "checked" }) 
            @Html.Encode(CurrCategory) <br />
        }
        else 
        {
            @Html.CheckBox(CurrCategory, false) 
            @Html.Encode(CurrCategory) <br />
        }
    } 
}