Reputation: 10115
Below is the Model
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; }
}
Below is View Model
public class VM_Project
{
public string[] SkillID { get; set; }
public List<M_ProjectType> ProjectType { get; set; }
}
Below is Get Action method. here I am getting the data for projects that will be sent to 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);
}
Below is 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>[email protected]</b></td>
</tr>
</tbody>
</table>
}
Below is Post Action Method
[HttpPost, Route("Project")]
public ActionResult Project(VM_Project project)
{
return View();
}
Question: I am getting project.ProjectType = null. Any suggestion why this is happening ?
Upvotes: 1
Views: 73
Reputation: 2177
I would recommend using EditorTemplates.
EditorTemplates
in you Views/Shared
direcotry.Create a partial view based on your type i.e. M_ProjectType.cshtml
Put your markup that you use in foreach
loop in M_ProjectType.cshtml
file
@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>[email protected]</b></td>
</tr>
</tbody>
Then render your editor template in your form like (note: no foreach
loop)
@Html.EditorFor(m=>m.ProjectType)
You should get correct model binded to your html elements back in controller.
Upvotes: 1
Reputation: 3717
Try this:
@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>
}
Upvotes: 0