我有一个应用程序和标签。由于配方可以具有多个标签,并且标签可以属于多个配方,因此我有以下模型:
public class Tag : IModel
{
[Key]
public int ID { get; set; }
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
public virtual ICollection<Recipe> Recipes { get;set; }
}
public class Recipe : IModel
{
[Key]
public int ID { get; set; }
[ForeignKey("Category")]
public int CategoryId { get; set; }
[Required(ErrorMessage = "The Title is required.")]
public string Title { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual Category Category { get; set; }
}
我的食谱控制器有一个HTTPGET编辑操作,该操作返回视图的配方:
public ActionResult Edit(int id = 0)
{
Recipe recipe = _recipeService.GetByID(id, "Category,Tags");
if (recipe == null)
{
return HttpNotFound();
}
CreateEditRecipeViewModel viewModel = new CreateEditRecipeViewModel(recipe, PopulateCategoryLookup(recipe));
return View(viewModel);
}
此时,配方的标签集合由我的getByid()方法填充。但是,我尚不清楚我应该如何在视图模型中添加一个集合,以便在视图中浮出水面。这是我当前的ViewModel:
public class CreateEditRecipeViewModel
{
[HiddenInput]
public int RecipeID { get; set; }
public int CategoryId { get; set; }
[Required(ErrorMessage = "The Title is required.")]
public string Title { get; set; }
}
在我看来,我想拥有一个文本盒,其中我将拥有一个逗号分开的标签列表(例如早餐,素食主义者,无麸质)。当提出编辑视图时,我希望它填充当前分配给食谱的每个标签的名称。当发布表单时,我想将标签列表拆分,然后在HTTPPOST编辑操作中,将值与ef。
调和。如果有人有代表视图中的复杂对象集合的指导,我将不胜感激!
谢谢,
chris
我通常使用listBoxfor标签与所选jQuery插件结合进行多选择。惊人的简单。我将努力看一下代码。但是我没有VS可以测试。类似:
public class CreateEditRecipeViewModel
{
[HiddenInput]
public int RecipeID { get; set; }
public int CategoryId { get; set; }
public List<int> TagIds { get; set; }
[Required(ErrorMessage = "The Title is required.")]
public string Title { get; set; }
}
//Then in view...
@Html.ListBoxFor(model => model.TagIds, HelperMethodToGetSelectListOfTags())
然后,就像您提到的那样,当您将视图模型重新转换为常规模型时,您只会将所选ID与EF调和。
这种方法的唯一缺点是您需要一些单独的代码来创建新标签。但是您没有提到这一点。
希望有帮助!