代码之家  ›  专栏  ›  技术社区  ›  rodbv

在没有窗体的情况下,如何将字符串数组发布到ASP.NET MVC控制器?

  •  172
  • rodbv  · 技术社区  · 16 年前

    我正在创建一个小应用程序来自学ASP.NET MVC和JQuery,其中一个页面是一些可以选择的项目列表。然后,我想按下一个按钮,并使用jquery的post函数向我的控制器发送一个包含所选项目的ID的列表(或类似的东西)。

    我设法得到一个数组,其中包含所选元素的ID,现在我想发布它。我可以这样做的一种方法是在我的页面中使用一个带有隐藏值的虚拟表单,然后用所选项目设置隐藏值,并发布该表单;不过,这看起来很简单。

    有没有一种更清洁的方法可以通过直接将阵列发送到控制器来实现这一点?我尝试了一些不同的方法,但看起来控制器无法映射它接收的数据。到目前为止,代码如下:

    function generateList(selectedValues) {
       var s = {
          values: selectedValues //selectedValues is an array of string
       };
       $.post("/Home/GenerateList", $.toJSON(s), function() { alert("back") }, "json");
    }
    

    然后我的控制器看起来像这样

    public ActionResult GenerateList(List<string> values)
    {
        //do something
    }
    

    我所得到的只是控制器参数中的一个“空”…

    有什么小窍门吗?

    9 回复  |  直到 7 年前
        1
  •  236
  •   MrDustpan    14 年前

    我修改了我的回复,将我做的测试应用程序的代码包括在内。

    更新:我已经更新了jquery,将“传统”设置设置为true,这样这将再次起作用(根据@dustindavis的回答)。

    首先是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
        });
    }
    

    这是我的控制器类中的代码:

    public JsonResult SaveList(List<String> values)
    {
        return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
    }
    

    当我调用这个javascript函数时,我得到一个警告,说“列表中的第一个项目:‘item1’”。希望这有帮助!

        2
  •  104
  •   Dustin Davis    13 年前

    仅供参考:jquery改变了它们序列化发布数据的方式。

    http://forum.jquery.com/topic/nested-param-serialization

    你必须将“传统”设置为“真”,否则

    { Values : ["1", "2", "3"] }
    

    会变成

    Values[]=1&Values[]=2&Values[]=3
    

    而不是

    Values=1&Values=2&Values=3
    
        3
  •  24
  •   Evgenii    13 年前

    谢谢大家的回答。另一个快速解决方案是 JQual.PARAM 方法与 传统的 参数设置为 要将JSON对象转换为字符串:

    $.post("/your/url", $.param(yourJsonObject,true));
    
        4
  •  8
  •   Alastair Pitts    14 年前

    不要将数据作为数组发布。 To bind to a list, the key/value pairs should be submitted with the same value for each key.

    您不应该需要表格来完成此操作。您只需要一个键/值对的列表,可以将其包括在对$.Post的调用中。

        5
  •  5
  •   Matas Vaitkevicius user3782709    10 年前

    .NET4.5 , MVC 5

    Javascript:

    JS中的对象: enter image description here

    发布的机制。

        $('.button-green-large').click(function() {
            $.ajax({
                url: 'Quote',
                type: "POST",
                dataType: "json",
                data: JSON.stringify(document.selectedProduct),
                contentType: 'application/json; charset=utf-8',
            });
        });
    

    C.*

    物体:

    public class WillsQuoteViewModel
    {
        public string Product { get; set; }
    
        public List<ClaimedFee> ClaimedFees { get; set; }
    }
    
    public partial class ClaimedFee //Generated by EF6
    {
        public long Id { get; set; }
        public long JourneyId { get; set; }
        public string Title { get; set; }
        public decimal Net { get; set; }
        public decimal Vat { get; set; }
        public string Type { get; set; }
    
        public virtual Journey Journey { get; set; }
    }
    

    控制器:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Quote(WillsQuoteViewModel data)
    {
    ....
    }
    

    接收的对象:

    enter image description here

    希望这能节省你一些时间。

        6
  •  4
  •   d.popov    10 年前

    另一个实现也在处理对象列表,而不仅仅是字符串:

    JS:

    var postData = {};
    postData[values] = selectedValues ;
    
    $.ajax({
        url: "/Home/SaveList",
        type: "POST",
        data: JSON.stringify(postData),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(data){
            alert(data.Result);
        }
    });
    

    假设“selectedvalues”是对象数组。

    在控制器中,参数是对应视图模型的列表。

    public JsonResult SaveList(List<ViewModel> values)
    {    
        return Json(new { 
              Result = String.Format("Fist item in list: '{0}'", values[0].Name) 
        });
    }
    
        7
  •  1
  •   Community CDub    7 年前

    正如我所讨论的 here ,

    如果您想将自定义JSON对象传递给MVC操作,那么您可以使用这个解决方案,它的工作方式很有魅力。

        public string GetData()
        {
            // InputStream contains the JSON object you've sent
            String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();
    
            // Deserialize it to a dictionary
            var dic = 
              Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<String, dynamic>>(jsonString);
    
            string result = "";
    
            result += dic["firstname"] + dic["lastname"];
    
            // You can even cast your object to their original type because of 'dynamic' keyword
            result += ", Age: " + (int)dic["age"];
    
            if ((bool)dic["married"])
                result += ", Married";
    
    
            return result;
        }
    

    这个解决方案的真正好处是,您不需要为每个参数组合定义新的类,除此之外,您还可以轻松地将对象强制转换为其原始类型。

    你可以使用这样的辅助方法来帮助你的工作

    public static Dictionary<string, dynamic> GetDic(HttpRequestBase request)
    {
        String jsonString = new StreamReader(request.InputStream).ReadToEnd();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
    }
    
        8
  •  0
  •   mr_squall    7 年前

    可以使用设置全局参数

    jQuery.ajaxSettings.traditional = true;
    
        9
  •  -1
  •   DavidW    14 年前

    这个答案在我的处境中帮了我很大的忙,所以谢谢你。 但是,为了将来的参考,人们应该绑定到一个模型,然后进行验证。这篇来自PhilHaack的文章描述了MVC 2的情况。 http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

    希望这能帮助别人。