I've searched around and can't find an answer to my problem.
I've got a View that takes accepts Foo
in like so:
@model IEnumerable<MyApplication.Models.Foo>
Inside of the view I've got a table. I populate the the table just doing a simple foreach
loop through my Foo
model. I have added a column where a user can add details to each row in a text area and save.
So the view looks like this:
@foreach (var item in Model)
{
<tr>
<th>
@using (Html.BeginForm("AddDetails", "MyController", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(u => item.Id)
@Html.TextAreaFor(u => item.Details, new { @class = "form-control" })
<input type="submit" value="Save" class="btn btn-sm btn-default" />
}
</th>
</tr>
}
My controller is setup like this:
[HttpPost]
public ActionResult AddDetails(Foo foo)
{
}
When I set a breakpoint on that controller foo
always has null
values for the Details
property and the Id
is always 0
. When it's passed into the view it's got all of the properties set to right, so I'm not sure why it is not posting back properly?
I've tried this:
@using (Html.BeginForm("AddDetails", "MyController", FormMethod.Post, new { foo = Model }))
I have also tried removing the foreach
loop and changing it to pass in just a single Model to the View and for the View to accept just the single model instead of an IEnumerable
. When I do this it posts back just fine.
And that does not work either. I'm wondering if it has something to do with the fact that my form is within a foreach
loop and perhaps I need to do a little more work like add a data-id
attribute to the element and just capture the click event on the button and do an AJAX call to the controller and pass the right values along that way?
EDIT Sorry I completely forgot the view model. Here is what that looks like:
public class Foo
{
public int Id { get; set; }
public string Details { get; set; }
}