Using Razor Views, how can I add X number of dependents to an Employee in a form?
So, I'm learning ASP.NET MVC and working on a project where you can add an Employee to a (mock) db of employees. Employees can have any number of dependents.
My View looks something like this:
<h2>Add New Employee</h2> @using (Html.BeginForm("NewEmployee", "Employee")) { <div class="form-group"> @Html.LabelFor(m => m.Employee.FirstName) @Html.TextBoxFor(m => m.Employee.FirstName, new { @class= "form-control" }) </div> <div class="form-group"> @Html.LabelFor(m => m.Employee.LastName) @Html.TextBoxFor(m => m.Employee.LastName, new { @class = "form-control" }) </div> <button type="submit" class="btn btn-primary">Add New Employee</button> }
This does work. I have the corresponding controller and action, and this employee does successfully get added to my mock db with the correct first and last name.
My Employee model looks like this:
public class Employee { public string Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public List<Dependent> Dependents { get; set; } }
As you can see, it has a list of Dependents. In the form View, I want to have a "Add Dependent" button that makes the corresponding first/last name fields appear. I also want the user to be able to add more than one, so I guess every time this "Add Dependent" button gets clicked, you get more fields.
My problems are:
1) How do I get pressing the "Add dependent" button to actually create new fields? I know I'm going to need JS for that, but I have no idea how I get that to mix with my View.
2) I have no idea how the post for that would work. Do I include a Dependents list in my viewmodel?
I know these are pretty big questions, so I don't really expect anyone to be able to show me exactly how it's done, but if anyone could point me in the right direction or show me some tutorial that can help, I'd really appreciate it.
0 comments:
Post a Comment