I would like to add items to a list in my model dynamically with java script. How can I make MVC bind the new item to the model?
My models:
public class Garage
{
public string Name{ get; set; }
public string Location { get; set; }
public IList<Car> Cars{ get; set; }
}
public class Car
{
public string Color{ get; set; }
public string Name { get; set; }
}
My view, which uses a Garage as model:
<% using (Html.BeginForm())
{%>
<div id="cars">
<%
foreach (var item in Model.Cars)
{
Html.RenderPartial("CarView", item);
} %>
</div>
<% } %>
And my CarView which uses a Car as model:
<div class="carRow">
<%-- Color--%>
<%=Html.CustomLabelFor(model => model.Color)%>
<%= Html.TextBox(Model.Color) %>
<%-- Name--%>
<%=Html.CustomLabelFor(model => model.Name)%>
<%= Html.TextBox(Model.Name) %>
</div>
When adding a new Car, I uses a AJAX call, and adds it to the html. The AJAX uses this method in the controller:
public ViewResult NewCar()
{
return View("CarView");
}
My java script ajax call:
$('.addCarButton').click(function () {
$.ajax({
url: "<%= Url.Action("CreateCars") %>",
cache: false,
success: function (html) { $("#cars").append(html); }
});
return false;
});
This renders the html nicely, but it does not add the car to the list of cars.
How can this be done?