正在尝试获取ID值为的“选定”复选框值
本文关键字:选定 复选框 获取 ID | 更新日期: 2023-09-27 18:14:20
下面是型号
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视图
@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();
}
问题:我正在做项目。ProjectType=null。有什么建议吗这是真的吗?
我建议使用EditorTemplates。
- 在
Views/Shared
目录中创建一个名为EditorTemplates
的文件夹 -
根据您的类型创建部分视图,即
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元素的正确模型。
试试这个:
@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>
}