function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
document.getElementById("myUL").appendChild(li);
}
我的控制器的方法(AddList)看起来像这样:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task NewShoppingList(object list)
{
// I don't know how to accept that list
}
但这样我的参数list是null.我怎样才能
用一些元素来获得它?
1> Hossein..:
ul并且li不是可提交的表单元素.您可以尝试以下操作.
我不确定你的视图模型是什么样的,但它看起来像一个字符串值列表?那么它在你的视图模型中会是这样的:
public class YourViewModel
{
public List Items { get; set; }
}
在您的视图中尝试以下操作:
item1
item2
/*...*/
itemN
function addHidden(theLi, key, value) {
// Create a hidden input element, and append it to the li:
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;'name-as-seen-at-the-server';
input.value = value;
theLi.appendChild(input);
}
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
addHidden(li, 'your-model-propertyName' + li-Count+1, inputValue );
document.getElementById("myUL").appendChild(li);
}
当您发布时,这些项目仍应在列表中.
[HttpPost]
[AllowAnonymous]
//[ValidateAntiForgeryToken]
public async Task NewShoppingList(List list)
{
// I don't know how to accept that list
}
如果您不想为每个li添加隐藏字段,您可以获取所有li项并使用Ajax发送它们.
像这样:
function sendData() {
var items = [];
$("#myUL li").map(function () {
items.push(this.innerText);
});
$.ajax({
type: "POST",
data: {
list: items
},
url: "/Home/NewShoppingList",
success: function (res) {
}
}