Reputation: 4928
Please i have a model class below
public class EditJob
{
public JobPost JobPost { get; set; }
public IEnumerable<JobRequirement> JobRequirement { get; set; }
public IEnumerable<JobResponsibility> JobResponsibility { get; set; }
}
I strongly bind the class to a view and want to use it for editing in controller. I have a controller which receives model like below.
[HttpPost]
public ViewResult SaveJob(EditJob model)
{
}
I Dynamically bind my Ienumerable to texboxes in my view like below.
@for (int i = 0; i < Model.JobResponsibility.Count();i++ )
{
JobWebsite.Domain.Enitities.JobResponsibility rs = Model.JobResponsibility.ElementAt(i);
<label class="control-label">Responsibility :</label>
Html.Hidden("Responsibility[" + i + "]", rs);
@Html.TextBoxFor(x => rs, new { @class = "form-control" }) <br />
}
On my button click, I realized the two IEnumerable methods from my model are not binding . The JobPosts in the model is not empty, yet my Ienumerable properties not always empty . I added a hidden field holding my values but i am having problem passing them to the controller. Please how do i achieve this ?
Upvotes: 0
Views: 1358
Reputation:
If you inspect you html, you will see that the controls name
attributes do not have the correct indexers for binding. Either change the collections to IList
and use as follows: (note you have not posted the model for JobResponsibility
so I'm assuming it contains properties ID
and Name
)
@for (int i = 0; i < Model.JobResponsibility.Count; i++ )
{
@Html.HiddenFor(m => m.JobResponsibility[i].ID)
@Html.TextBoxFor(m => m.JobResponsibility[i].Name)
}
Alternatively, create a custom EditorTemplate
for type of JobResponsibility
/Views/Shared/EditorTemplates/JobResponsibility.cshtml
@model JobResponsibility
@Html.HiddenFor(m => m.ID)
@Html.TextBoxFor(m => m.Name)
and in the main view
@model EditJob
@using(Html.BeginForm())
{
.....
@Html.EditorFor(m => m.JobResponsibility)
....
}
Upvotes: 1
Reputation: 28107
I can't see anything at the moment binding to JobResponsibility
.
Try changing
Html.Hidden("Responsibility[" + i + "]", rs);
to
Html.Hidden("JobResponsibility[" + i + "]", rs);
Upvotes: 0