[英]How can I access a JavaScript array in my MVC controller?
I've created an array inside a javascript. 我在javascript中创建了一个数组。 Now I want to use the array controller.
现在,我想使用阵列控制器。 Currently I'm using
FormCollection
to access data from the form. 目前,我正在使用
FormCollection
来访问表单中的数据。 Is there a way to access my javascript array in FormCollection
or as a parameter in the Html.BeginForm()
? 有没有办法在
FormCollection
或作为Html.BeginForm()
的参数来访问我的JavaScript数组?
I've tried doing a JSON post using some examples I found on the forum but the array was null in the controller. 我尝试使用在论坛上找到的一些示例进行JSON发布,但该数组在控制器中为null。 Can you please help with the best approach to accessing my javascript array in the controller?
您能否以最好的方法来帮助您访问控制器中的JavaScript数组?
<script type="text/javascript">
var $checkboxes = $('input[type="checkbox"]');
$(document).ready(function () {
$('#saveBtn').click(function () {
var checkList = new Array();
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
checkList.push('checked');
}
else
checkList.push('unchecked');
});
alert(checkList);
});
});
</script>
UPDATE 1 更新1
$(document).ready(function () {
$('#saveBtn').click(function () {
var options= [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item={ "UserChoice" : "checked", "OptionID": "YouCanSetIDHere"};
}
else
{
var item={ "UserChoice" : "unchecked", "OptionID": "YouCanSetIDHere"};
}
options.push(item);
}
$.ajax({ type: "POST", url: '@Url.Action("Edit","Attendance")',
contentType: "application/json",
data: JSON.stringify(options)
}).done(function (html) {
//do something with the response.
});
});
});
You can create items which is similar to your viewmodel and push that to your array and post it using jQuery post. 您可以创建与视图模型相似的项目,并将其推入数组并使用jQuery post发布。 In your controller action, you can use a collection of your viewmodel to accept it.
在控制器操作中,可以使用视图模型的集合来接受它。 MVC model binding will take care of the rest.
MVC模型绑定将处理其余的工作。
Assume you have a ViewModel like this 假设您有一个这样的ViewModel
public class UserOptionVM
{
public string OptionID{ set;get;}
public string UserChoice { set;get;}
}
And in your Action method, you accept a collection of this 在您的Action方法中,您接受了以下内容的集合
[HttpPost]
public ActionResult Save(List<UserOptionVM> model)
{
// loop through collection and read and save
}
Now change your Js file to send something which match with our viewmodel. 现在,更改您的Js文件以发送与我们的视图模型匹配的内容。
var options= [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item={ "UserChoice" : "checked", "OptionID": "YouCanSetIDHere"};
}
else
{
var item={ "UserChoice" : "unchecked", "OptionID": "YouCanSetIDHere"};
}
options.push(item);
});
$.ajax({ type: "POST",
url: "@Url.Action("Save","User")",
contentType: "application/json",
data: JSON.stringify(options)
}).done(function (html) {
//do something with the response.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.