如何在没有表单的情况下将字符串数组发布到 ASP.NET MVC 控制器? [英] How can I post an array of string to ASP.NET MVC Controller without a form?
问题描述
我正在创建一个小应用程序来自学 ASP.NET MVC 和 JQuery,其中一个页面是一个项目列表,其中可以选择一些项目.然后我想按下一个按钮并使用 JQuery 的 Post 函数向我的控制器发送一个列表(或类似的东西),其中包含所选项目的 ID.
I am creating a small app to teach myself ASP.NET MVC and JQuery, and one of the pages is a list of items in which some can be selected. Then I would like to press a button and send a List (or something equivalent) to my controller containing the ids of the items that were selected, using JQuery's Post function.
我设法获得了一个包含所选元素 ID 的数组,现在我想发布它.我可以这样做的一种方法是在我的页面中有一个带有隐藏值的虚拟表单,然后使用所选项目设置隐藏值,然后发布该表单;不过,这看起来很粗糙.
I managed to get an array with the ids of the elements that were selected, and now I want to post that. One way I could do this is to have a dummy form in my page, with a hidden value, and then set the hidden value with the selected items, and post that form; this looks crufty, though.
是否有更简洁的方法来实现这一点,将数组直接发送到控制器?我尝试了一些不同的东西,但看起来控制器无法映射它接收的数据.这是到目前为止的代码:
Is there a cleaner way to achieve this, by sending the array directly to the controller? I've tried a few different things but it looks like the controller can't map the data it's receiving. Here's the code so far:
function generateList(selectedValues) {
var s = {
values: selectedValues //selectedValues is an array of string
};
$.post("/Home/GenerateList", $.toJSON(s), function() { alert("back") }, "json");
}
然后我的控制器看起来像这样
And then my Controller looks like this
public ActionResult GenerateList(List<string> values)
{
//do something
}
我设法得到的只是控制器参数中的空"...
All I managed to get is a "null" in the controller parameter...
有什么建议吗?
推荐答案
我修改了我的回复以包含我所做的测试应用程序的代码.
I modified my response to include the code for a test app I did.
更新:我已经更新了 jQuery 以将传统"设置设置为 true,这样这将再次起作用(根据 @DustinDavis 的回答).
首先是 javascript:
First the javascript:
function test()
{
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };
$.ajax({
type: "POST",
url: "/Home/SaveList",
data: postData,
success: function(data){
alert(data.Result);
},
dataType: "json",
traditional: true
});
}
这是我的控制器类中的代码:
And here's the code in my controller class:
public JsonResult SaveList(List<String> values)
{
return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}
当我调用那个 javascript 函数时,我收到一条提示列表中的第一项:'item1'".希望这会有所帮助!
When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!
这篇关于如何在没有表单的情况下将字符串数组发布到 ASP.NET MVC 控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!