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

本文关键字:model gt property But @Html MVC EditorFor ASP NET | 更新日期: 2023-09-27 18:22:16

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

@{
            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语句中,如何访问模型。像我这样的类别在@Html.EditorFor(model => model.Id)???

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

我会使用强类型视图。创建一个包含您的模型的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 />
        }
    } 
}