使用list属性的自定义编辑器模板

本文关键字:编辑器 自定义 list 属性 使用 | 更新日期: 2023-09-27 18:15:58

我几乎得到了它的工作,但我错过了一个微小的一点知识,使这项工作,这是一个快速修复我知道它。

我把两个ViewModels放到一个视图中:

public class MajorViewModel
{
    public ICollection<Major> Majors { get; set; }
}
public class MinorViewModel
{
    public ICollection<Minor> Minors { get; set; }
}

进入如下视图:

<snip>
@Html.Partial("_MajorPartial")
@Html.Partial("_MinorPartial")
<snip>

视图如下:

// _MajorPartial
@using Microsoft.AspNet.Identity
@model ClassPlannerMVC.ViewModels.MajorViewModel
@using (Html.BeginForm())
{
     //@Html.EditorFor(m => m.Majors) ?? I'm not able to use this here
}
// _MinorPartial
looks the same except "Major" is changed to "Minor"

然后我在views/Shared/EditorTemplates/Major中有两个视图。cshtml和Minor.cshtml

// Major.csthml
@model ClassPlannerMVC.Models.Major
@Html.HiddenFor(m => m.ID)
<div class="form-group">
    @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.EditorFor(m => m.Name, new { @class = "form-control" })
    </div>
</div>
// Minor.cshtml
looks the same except "Major" is changed to "Minor"

我的两个模型是:

public class Major
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<UserHasMajor> UserHasMajors { get; set; }
}
public class Minor
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<UserHasMinor> UserHasMinors { get; set; }
}

当前视图不显示我的视图模型(MajorViewModel, MinorViewModel),它们将分别显示Major和Minor的编辑器。我知道我可能会传递一些错误的东西到_MajorPartial和_MinorPartial视图,这就是为什么我不能添加@Html。EditorFor(x => x. majors)将显示我的自定义编辑器模板。有一些非常小的缺失在我的代码,你发现我的错误吗?

如果有必要我会上传更多的代码

使用list属性的自定义编辑器模板

你似乎没有传递任何东西给你的@Partial()方法(即模型为null)。我建议您创建另一个视图模型来容纳两者并将其传递给主视图,例如

public class CombinedViewModel
{
  public MajorViewModel MajorVM { get; set; }
  public MinorViewModel MinorVM { get; set; }
}

在你的[HttpGet]方法中,填充视图模型并传递给主视图

public ActionResult Details()
{
  CombinedViewModel model = new CombinedViewModel();
  // set properties
  model.MajorVM = new MajorVM();
  model.MajorVM.Majors = // assign your collection
  ..
  return View(model);
}

然后在主视图

@model YourAssembly.CombinedViewModel
...
@Html.Partial("_MajorPartial", Model.MajorVM)
@Html.Partial("_MinorPartial", Model.MinorVM)

或者,只有一个具有属性public ICollection<Major> Majors { get; set; }public ICollection<Minor> Minors { get; set; }的视图模型(不确定您是否为了简洁而省略了一些其他属性,因此您需要具有单独的视图模型)