I use ASP.NET MVC 5. I am trying (without success :|) to create a form and one of the parameters of this form is a list. I am in trouble about how to add/remove/update element for this list. I tried a lot of different samples (with ajax, kendo ui and more) with no success.
Simplified problem:
I want to be able to add House information in a database. Each House got information and a list of Occupants
Details: - my occupants are not saved anywhere. so no access to a db or other - there is nothing created before I press the Create House button. Everything as to stay/be created in this page - the solution can even use kendo ui - I am looking for a very simple solution :)
Thanks a lot!
public class House
{
[Key]
public int HouseID { get; set; }
public string Address { get; set; }
public int RoomsCount;
public List<Occupant> OccupantsList { get; set; }
}
public class Occupant
{
public string Name { get; set; }
public int Age { get; set; }
}
Create House page
@model DeveloperConsole.Models.House
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Houses</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@RenderBody()
<div class="form-horizontal">
<h4>House</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<dl class="dl-horizontal">
<dt class="form-group">
@Html.LabelFor(model => model.Address)
</dt>
<dd class="col-md-10">
@Html.EditorFor(model => model.Address)
</dd>
<dt class="form-group">
@Html.LabelFor(model => model.RoomsCount)
</dt>
<dd class="col-md-10">
@Html.EditorFor(model => model.RoomsCount)
</dd>
<dd class="form-group">
@if (Model.OccupantsList.Count > 0)
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.OccupantsList[0].Name)
</th>
<th>
@Html.DisplayNameFor(model => model.OccupantsList[0].Age)
</th>
</tr>
@foreach (var template in Model.OccupantsList)
{
Html.RenderPartial("Occupant", template);
}
</table>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Add an Occupant" class="btn btn-default" />
</div>
</div>
</dd>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="command" value="Create House" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
Occupant partial view
@model DeveloperConsole.Models.Occupant
<div class="editorRow">
<tr>
<td>
@Html.EditorFor(model => model.Name)
</td>
<td>
@Html.EditorFor(model => model.Age)
</td>
<td>
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Delete this Occupant" class="btn btn-default" />
</div>
</td>
</tr>
</div>