我怎么能不张贴形式的字符串数组ASP.NET MVC控制器? [英] How can I post an array of string to ASP.NET MVC Controller without a form?

查看:68
本文介绍了我怎么能不张贴形式的字符串数组ASP.NET MVC控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个小的应用程序来教自己的ASP.NET MVC和JQuery,和一个网页是一些可以选择的项目列表。然后,我想preSS一个按钮,发送一个List(或等值的东西),含中选定的项目,使用jQuery的POST功能的IDS我的控制器。

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.

有一个清洁的方式直接发送阵列到控制器来实现这一点,?我已经尝试了一些不同的东西,但它看起来像控制器不能映射它接收数据。这里的code迄今:

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...

任何提示?

推荐答案

我修改我的回应包括code的测试程序我做到了。

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
    });
}

这是在我的控制器类code:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆