我想用java腳本動態地將項目添加到我的模型中的列表中。我如何讓MVC將新項目綁定到模型?如何在javascript中添加項目到MVC模型?
我的模型:
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; }
}
我的看法,它採用了車庫爲模型:
<% using (Html.BeginForm())
{%>
<div id="cars">
<%
foreach (var item in Model.Cars)
{
Html.RenderPartial("CarView", item);
} %>
</div>
<% } %>
而且我Carview會它採用了轎車的典範:
<div class="carRow">
<%-- Color--%>
<%=Html.CustomLabelFor(model => model.Color)%>
<%= Html.TextBox(Model.Color) %>
<%-- Name--%>
<%=Html.CustomLabelFor(model => model.Name)%>
<%= Html.TextBox(Model.Name) %>
</div>
加入當一個新車,我使用AJAX調用,並將其添加到HTML。 的AJAX使用此方法控制器:
public ViewResult NewCar()
{
return View("CarView");
}
我的Java腳本調用Ajax:
$('.addCarButton').click(function() {
$.ajax({
url: "<%= Url.Action("CreateCars") %>",
cache: false,
success: function (html) { $("#cars").append(html); }
});
return false;
});
這很好地呈現HTML,但它並不車添加到汽車的列表。
這怎麼辦?
它不需要添加一個JavaScript點擊處理程序。這些變量已經在MVC中提供。 – spons