EditorTemplate +型号不上POST返回(EditorTemplate + Model

2019-10-31 21:56发布

我似乎无法想出解决办法,这是推动我疯了!

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

我有一个视图模型:

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属性为null:

    [HttpPost]
    public ActionResult Membership(UserMembershipViewModel model)
    {

        // model IS NULL!!

        return View(model);
    }

任何帮助将不胜感激!

Answer 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)


文章来源: EditorTemplate + Model not being returned on POST