0

我似乎无法弄清楚这一点,这让我发疯!

本质上,我有一个需要显示的行列表,每行一个下拉列表。

我有一个视图模型:

public class UserMembershipViewModel:BaseViewModel
{
    public List<ProgramMembership> ProgramMembership { get; set; }
}

在我的父视图中,您可以看到我正在使用位于“/Views/Shared/EditorTemplates/ProgramMembership.cshtml”中的编辑器模板:

@using AcnCS.Model
@model AcnCS.Model.ViewModels.User.UserMembershipViewModel 
@{
    ViewBag.PageHeader = "Membership for " + Model.User.FullName;
    ViewBag.PageTitle = "Membership for " + @Model.User.FullName;
    ViewBag.HideNav = true;
}

    @if (Model.ProgramMembership != null)
    {
        <div class="row-fluid">
            <div class="span12">
                <div id="permissions">
                    @using (Html.BeginForm())
                    {
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <td>Program</td>
                                    <td>Effective Membership?</td>
                                    <td>Permission Type</td>
                                </tr>
                            </thead>
                             @Html.EditorFor(m => Model.ProgramMembership, "ProgramMembership")

                        </table>
                        <input type="submit" class="btn btn-primary" value="Save Changes"/>
                    }

                </div>

            </div>
        </div>
    }

我的编辑器模板 (ProgramMembership.cshtml) 是:

@using AcnCS.Model
@model List<AcnCS.Model.ProgramMembership>

@foreach(ProgramMembership membership in Model)
{
    <tr>
        <td>@membership.ProgramName</td>
        <td>
            @if (membership.IsMember)
            {
                <span class="label label-success">@membership.IsMember</span>
            }
            else
            {
                @membership.IsMember
            }
        </td>
        <td>@Html.DropDownListFor(x => membership.PermissionType, membership.PermissionTypes)</td>
    </tr>
}

一切都正常显示,但是当我提交时,我的模型对象为空,甚至模型中的 ProgramMembership 属性也为空:

    [HttpPost]
    public ActionResult Membership(UserMembershipViewModel model)
    {

        // model IS NULL!!

        return View(model);
    }

任何帮助将不胜感激!

4

1 回答 1

1

我会将属性名称复数,因为它是一个集合,以提高可读性

public class UserMembershipViewModel:BaseViewModel
{
    public List<ProgramMembership> ProgramMemberships { get; set; }
}

并且您的 EditorTemplate 文件中不需要循环

@model AcnCS.Model.ProgramMembership
<tr>
    <td>@membership.ProgramName</td>
    <td>
      @if (membership.IsMember)
      {
         <span class="label label-success">@membership.IsMember</span>
      }
      else
      {
         @membership.IsMember
      }
    </td>
    <td>@Html.DropDownListFor(x => membership.PermissionType, membership.PermissionTypes)</td>
</tr>

在您的主视图中,像这样调用您的 EditorTemplate

@Html.EditorFor(m=>m.ProgramMemberships)
于 2012-07-12T18:30:37.897 回答