如何将项目添加到MVC模式在JavaScript? [英] How to add items to MVC model in javascript?
问题描述
我想用项目Java脚本动态地添加到列表在我的模型。我怎样才能让MVC新项目绑定到模型?
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?
我的模型:
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>
<% } %>
和我Carview会它采用了轿车,型号:
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>
在添加新的车,我使用了AJAX调用,并将其添加到HTML。
AJAX的使用此方法控制器:
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");
}
我的Java脚本调用Ajax:
My java script ajax call:
$('.addCarButton').click(function () {
$.ajax({
url: "<%= Url.Action("CreateCars") %>",
cache: false,
success: function (html) { $("#cars").append(html); }
});
return false;
});
此呈现的HTML很好,但它不轿厢添加到汽车的列表。
This renders the html nicely, but it does not add the car to the list of cars.
如何才能做到这一点?
推荐答案
您可以看看的的 下面的文章
在史蒂芬·桑德森提供了一个分步教程如何实现这一点。
You may take a look at the following article
in which Steven Sanderson provides a step by step tutorial on how to implement this.
这篇关于如何将项目添加到MVC模式在JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!