jQuery 如何在javascript中向MVC模型添加项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16955101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add items to MVC model in javascript?
提问by eflles
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?
我想使用 java 脚本动态地将项目添加到我的模型中的列表中。如何让 MVC 将新项目绑定到模型?
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:
我的 CarView 使用 Car 作为模型:
<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:
添加新车时,我使用 AJAX 调用,并将其添加到 html。AJAX 在控制器中使用此方法:
public ViewResult NewCar()
{
return View("CarView");
}
My java script ajax call:
我的java脚本ajax调用:
$('.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.
这可以很好地呈现 html,但它不会将汽车添加到汽车列表中。
How can this be done?
如何才能做到这一点?
回答by Darin Dimitrov
You may take a look at the following article
in which Steven Sanderson provides a step by step tutorial on how to implement this.
您可以查看following article
Steven Sanderson 提供的有关如何实现这一点的分步教程。
回答by Kevin Fichter
I realize that this is an old question, but after trying the above suggestion re Steven Sanderson's BeginCollectionItem, and a number of other potential solutions, I did not get very far (new items would not post). BeginCollectionItem seemed like a nice solution in theory, but it would not post new items, and it had unexpected effects on formatting of the list items.
我意识到这是一个老问题,但是在尝试了上述关于Steven Sanderson 的 BeginCollectionItem 的建议以及许多其他潜在解决方案之后,我并没有走得很远(新项目不会发布)。BeginCollectionItem 理论上似乎是一个不错的解决方案,但它不会发布新项目,并且对列表项目的格式有意想不到的影响。
The solution wound up being surprisingly simple, and did not require any external libraries (beyond JQuery). This works for me in ASP.NET MVC5.
该解决方案令人惊讶地简单,并且不需要任何外部库(除了 JQuery)。这在 ASP.NET MVC5 中对我有用。
- Create an editor template for the row item.
- 为行项目创建一个编辑器模板。
path: Views/Shared/EditorTemplate/NuggetSourceDto.cshtml
路径:Views/Shared/EditorTemplate/NuggetSourceDto.cshtml
@model [namespace].NuggetSourceDto
@{
ViewBag.Title = "NuggetSourceDto";
}
<li [email protected]>
@Html.HiddenFor(t => t.Id)
@Html.TextBoxFor(s => s.Url, new { @class = "form-control", autofocus = "autofocus" })
<a role="button" class="glyphicon glyphicon-remove"></a>
</li>
- Use the above template (the following runs through the collection and generates html for each item):
- 使用上述模板(以下内容贯穿整个集合并为每个项目生成 html):
In my view:
在我看来:
@Html.EditorFor(m => m.NuggetSources);
- When a user clicks the 'add row' button ('addSourceBtn' in my code below), I use ajax to get the html for the template.
- 当用户单击“添加行”按钮(下面代码中的“addSourceBtn”)时,我使用 ajax 获取模板的 html。
MVC controller get method:
MVC控制器获取方法:
[HttpGet]
public PartialViewResult AddBlankSourcesRow()
{
return PartialView("EditorTemplates/NuggetSourceDto", new NuggetSourceDto());
}
js handler:
js处理程序:
$(document).ready(function () {
$('#addSourceBtn').click(function () {
var indexOfNewItem = $('#sourceList li').length;
$.ajax({
url: '/nugget/AddBlankSourcesRow/',
cache: false,
success: function (html) {
var newItem = $(html);
var randId = Math.random() * 10000000;
randId = Math.floor(randId);
newItem.attr('id', 'newSource__' + randId);
newItem.find('input').first().attr({
//name: 'NuggetSources[3].Id'
name: 'NuggetSources[' + indexOfNewItem + '].Id',
id: 'NuggetSources_' + indexOfNewItem + '__Id',
value: randId
});
newItem.find('input[id^=Url]').attr({
name: 'NuggetSources[' + indexOfNewItem + '].Url',
id: 'NuggetSources_' + indexOfNewItem + '__Url'
});
$('#sourceList').append(newItem);
}
});
return false;
});
});
The lynchpin in all of this is to ensure that the newly-inserted element has a name attribute for each property that includes the name of the collection and a valid index:
所有这一切的关键是确保新插入的元素对每个属性都有一个 name 属性,其中包括集合的名称和有效的索引:
newItem.find('input').first().attr({
//name: 'NuggetSources[3].Id'
name: 'NuggetSources[' + indexOfNewItem + '].Id'
});
newItem.find('input[id^=Url]').attr({
name: 'NuggetSources[' + indexOfNewItem + '].Url'
});
Without this, the new items are ignored in the MVC controller.
如果没有这个,MVC 控制器中的新项目将被忽略。
This solution only handles adding new rows. For deletions, because the indexing is important, one solution is to fire a delete request to the server and then reload the list, or just fix the existing indices in js.
此解决方案仅处理添加新行。对于删除,因为索引很重要,一种解决方案是向服务器发出删除请求,然后重新加载列表,或者只是修复 js 中现有的索引。
回答by suraj mahajan
Follow this jQuery plugin , specially designed for adding new element client side in detailed part of transaction
按照这个jQuery插件,专门为在事务的详细部分添加新元素客户端而设计的