Pat*_*ott 3 c# asp.net-mvc jquery asp.net-mvc-3
使用asp.net mvc3和jquery
我在页面上有x个表单,每个表单在用户添加新项目时创建.每个表单代表c#中的模型.每个表单都有一个字符串列表作为其中一个属性.我想要一个提交所有表单的全部保存按钮,但我想在它之前将它们序列化为一个对象列表,然后在后端对其进行排序.我怎么能用jQuery做到这一点?
<form>
<input name="ListThing" value="one" />
<input name="ListThing" value="two" />
<input name="ListThing" value="three" />
<input name="Name" value="Bob" />
</form>
<form>
<input name="ListThing" value="one" />
<input name="ListThing" value="two" />
<input name="ListThing" value="three" />
<input name="Name" value="Pat" />
</form>
Run Code Online (Sandbox Code Playgroud)
C#
public class myModel{
public List<string> ListThing {get; set;}
public string Name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
controller - UploadController -action
[HttpPost]
public ActionResult SaveAll( List<myModel> myModels )
{
// do stuff
return View();
}
Run Code Online (Sandbox Code Playgroud)
您不能拥有具有相同ID的多个元素.首先修复你的标记:
<form>
<input name="ListThing" value="one" />
<input name="ListThing" value="two" />
<input name="ListThing" value="three" />
<input name="Name" value="Bob" />
</form>
<form>
<input name="ListThing" value="one" />
<input name="ListThing" value="two" />
<input name="ListThing" value="three" />
<input name="Name" value="Pat" />
</form>
Run Code Online (Sandbox Code Playgroud)
然后假设您有一些链接来触发操作:
@Html.ActionLink("Save all", "SaveAll", "Home", null, new { id = "saveall" })
Run Code Online (Sandbox Code Playgroud)
你可以简单地AJAX化它:
$('#saveall').click(function () {
var data = $('form').map(function () {
var $form = $(this);
return {
name: $form.find(':input[name=Name]').val(),
listThing: $form.find(':input[name=ListThing]').map(function () {
return $(this).val();
}).toArray()
};
}).toArray();
$.ajax({
url: this.href,
type: 'post',
contentType: 'application/json',
data: JSON.stringify({ myModels: data }),
success: function (result) {
alert('done');
}
});
return false;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5857 次 |
| 最近记录: |