jquery - 如何在 JavaScript 中向 MVC 模型添加项目?

标签 jquery asp.net-mvc asp.net-mvc-4

我想使用 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/

相关文章:

asp.net-mvc - MicrosoftMvcValidation.js VS jquery.validate.js(Bassistance)

c# - WCF web服务和getJSON为跨域调用返回空数据

javascript - 在javascript中使用鼠标调整文本/div的大小

asp.net - 关于使用 ASP.net WebForms 或 MVC 的建议

asp.net-mvc-4 - 带有外部数据和 TypeScript : compile error "Cannot set property ' gridDim' of undefined"的 Ng-grid

linq - "group by"在 LINQ 中如何工作?错误 "' 对象'不包含 'type' 的定义“

jquery - jqgrid 中的页面计数与服务器端分页

javascript - 展开/折叠多选标签 (optgroup)

javascript - Codeigniter-PHP : How to Change table week Dates , 更改输入日期

javascript - jQuery周历约会只在Chrome中出现,其他浏览器不出现