Reputation: 391
I am trying to create an edit form for each model in an IEnumerable
of models. Basically, my Index.cshtml page has a table of every object from my database table and I want to add an edit form for each model. However, for whatever reason whenever I post an individual form, the data all gets passed as NULL.
Here is what I have:
Model:
public partial class Person
{
public int id { get; set; }
public string name { get; set; }
}
Controller:
public async Task<IActionResult> Index()
{
return View(await _context.ASNGFellows.ToListAsync());
}
public async Task<IActionResult> Edit(Person person)
{
if (ModelState.IsValid)
{
#update database object
}
return View(Person)
}
View (Index.cshtml):
@model IEnumerable<Person>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
<th class="actionItemsTh">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
<a href="#" class="edit">Edit</a>
</td>
</tr>
<tr>
<td colspan="5">
<div>
<form method="post" asp-action="Edit">
@Html.AntiForgeryToken()
@Html.HiddenFor(modelItem => item.id)
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(modelItem => item.name)
@Html.EditorFor(modelItem => item.name)
@Html.ValidationMessageFor(modelItem => item.name)
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</td>
</tr>
}
</tbody>
</table>
The form generates properly and when I submit, it hits the controller method, however the person
object has null values. What am I doing wrong here?
Upvotes: 0
Views: 477
Reputation: 7190
You can change your form like following.
<form method="post" asp-action="Edit">
@Html.AntiForgeryToken()
<input type="hidden" name="person.id" value="@item.id"/>
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(modelItem => item.name)
<input type="text" name="person.name" value="@item.name" />
@Html.ValidationMessageFor(modelItem => item.name)
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
Controller:
[HttpPost]
public async Task<IActionResult> Edit(Person person)
{
if (ModelState.IsValid)
{
}
return View(person);
}
Upvotes: 1