Let's say that I have a view, whose purpose is to show a table with some information about a person entity. The view contains a form with an input element that the user can use to add a new person to the table by entering its name.
My question is: In this scenario, is there a convention about where to put hidden fields that are needed to retrieve the data in the server again?
In my code, I put them in the table definition; but maybe it's best to put all those fields together inside a div
or something. Maybe it just doesn't matter where you put those as long as the code works. I'm just curious because I like to generate the best HTML possible.
I understand that this type of operation is very expensive to archive using a full post-back to the server, and an Ajax request will be better in this scenario, but still the question remains valid.
This is the model for the view:
class IndexViewModel
{
public string Query { get;set; }
public IList<Person> People { get;set; }
}
And the view:
<form action="home/index">
<input id="query" name="query"/>
<input type="submit" value"Add"/>
<table>
<tbody>
<tr>
<th>Name</th>
<th></th>
</tr>
@for (int i = 0; i < Model.People.Count; ++i)
{
<tr>
<td>
@Html.HiddenFor(m=>m.People[i].Id)
@Html.ActionLink(Model.People[i].Name, "Details", "Person", new { id = Model.People[i].Id }, null)
</td>
<td>
@Html.ActionLink("Remove", "RemovePerson", "Home", new { id = Model.People[i].Id }, null)
</td>
</tr>
}
</tbody>
</table>
</form>
In the Action I receive the model and get the list of people again from the database and add the new person.
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
// Here I load again all people in the view and add the new that was queried.
for (int i = 0; i < model.People.Count; ++i)
model.People[i] = db.FindById(model.People[i].Id);
var newPerson = db.FindByName(model.Query);
if (newPerson != null)
model.People.Add(newPerson);
return View(model);
}
:)
. Us cheery regulars are just trying to keep the site as tidy as possible! \$\endgroup\$