以下是模型
public class M_ProjectType
{
public Int16 ProjectTypeID { get; set; }
public String ProjectType { get; set; }
public Boolean IsActive { get; set; }
public Decimal Cost { get; set; }
public String Description { get; set; }
public Boolean IsChecked { get; set; }
}
以下是视图模型
public class VM_Project
{
public string[] SkillID { get; set; }
public List<M_ProjectType> ProjectType { get; set; }
}
以下是Get Action方法。在这里,我将获取将发送到View Model的项目数据
[HttpGet, Route("Project")]
public async Task<ActionResult> Project()
{
var projectTypes = (await _projectTypes.ProjectTypesList()).Value;
var list = new List<M_ProjectType>();
foreach (var item in projectTypes)
{
list.Add(new M_ProjectType
{
Cost = item.Cost,
Description = item.Description,
IsActive = item.IsActive,
IsChecked = false,
ProjectType = item.ProjectType,
ProjectTypeID = item.ProjectTypeID
}
);
}
var project = new VM_Project
{
ProjectType = list
};
return View(project);
}
以下是Razor View
@foreach (var item in Model.ProjectType)
{
<table class="table table-striped">
<tbody>
<input type="hidden" value="@item.ProjectTypeID" name="ProjectTypeID" />
<tr>
<td style="width:5%">
@Html.CheckBoxFor(i => item.IsChecked, new { @class = "tableflat" })
@Html.HiddenFor(i => item.ProjectTypeID)
</td>
<td style="width:10%">@item.ProjectType</td>
<td style="width:80%">@item.Description</td>
<td style="width:5%"><b>$@item.Cost</b></td>
</tr>
</tbody>
</table>
}
以下是发布操作方法
[HttpPost, Route("Project")]
public ActionResult Project(VM_Project project)
{
return View();
}
问题:我正在获取project.ProjectType = null。任何建议为什么 这发生了吗?
答案 0 :(得分:1)
我建议使用EditorTemplates。
EditorTemplates
direcotry中创建名为Views/Shared
的文件夹。根据您的类型创建部分视图,例如M_ProjectType.cshtml
将foreach
循环中使用的标记放在M_ProjectType.cshtml
文件中
@model M_ProjectType
<table class="table table-striped">
<tbody>
<tr>
<td style="width:5%">
@Html.CheckBoxFor(i => i.IsChecked, new { @class = "tableflat" })
@Html.HiddenFor(i => i.ProjectTypeID)
</td>
<td style="width:10%">@Model.ProjectType
@Html.HiddenFor(i=>i.ProjectType)
</td>
<td style="width:80%">@Model.Description</td>
<td style="width:5%"><b>$@Model.Cost</b></td>
</tr>
</tbody>
然后在表单中呈现您的编辑器模板(注意:没有foreach
循环)
@Html.EditorFor(m=>m.ProjectType)
你应该在控制器中找到与你的html元素绑定的正确模型。
答案 1 :(得分:0)
试试这个:
@foreach (var item in Model.ProjectType)
{
<table class="table table-striped">
<tbody>
<tr>
<td style="width:5%">
@Html.CheckBoxFor(i => item.IsChecked, new { @class = "tableflat" })
@Html.HiddenFor(i => item.ProjectTypeID, new { @Value = item.ProjectTypeID})
</td>
</tr>
</tbody>
</table>
}