我想使用 java 脚本动态地将项目添加到模型中的列表中。如何使 MVC 将新项目绑定(bind)到模型?
我的模型:
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 在 Controller 中使用此方法:
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,但它不会将汽车添加到汽车列表中。
如何做到这一点?
最佳答案
您可以查看following article
其中 Steven Sanderson 提供了有关如何实现这一点的分步教程。
关于jquery - 如何在 JavaScript 中向 MVC 模型添加项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16955101/