如何将Javascript字符串数组发送到控制器并呈现部分视图

时间:2013-02-23 21:20:53

标签: javascript ajax jquery asp.net-ajax

我有这个问题。

  • 我在JavaScript中有一个数组如下:

    checkedItems = { “1000”, “1001”, “1002”}

  • 我需要将此数组发送到C#controller

  • 当控制器完成此阵列的工作时,返回PartialView
  • 将呈现PartialView

我尝试了一切,但没有任何作用。

这是我的Javascript:

function getAllCheckedFirsts()
{
    var postIds = {
        data: []
    };

    var i = 0;
    $(":checked[id$='-first']").each(function (){
        var id = $(this).attr("id");
        var words = id.split("-");
        postIds.data.push(words[0]);
        i++;
    });

    $.post("/Home/getInfoAboutChecked", postIds);
}

这是我的控制者:

[HttpPost]
public PartialViewResult getInfoAboutChecked(string[] data)
{
    List<EntityModel> model = new List<EntityModel>();
    if (data.Length != 0)
    {
        int id = 0;
        WSEntityInfo entity;
        WSPropertyInfo[] fids;
        foreach (var e in data)
        {
            id = Convert.ToInt32(e);
            entity = WSConnect.getEntityInfo(id);
            fids = WSConnect.getAllFidsAsWSPropertyInfo(id);
            model.Add(new EntityModel(entity, fids));
        }               
    }
    return PartialView("_EntitiesView",model);
}

但控制器中的数据仍为NULL 问题是什么 ?还有一个问题,我在哪里以及如何在html中定义渲染的位置。 感谢帮助

2 个答案:

答案 0 :(得分:1)

$.post("/Home/getInfoAboutChecked", JSON.stringify(postIds.data));

你可以使用@Url.Action to渲染链接,所以假设作为控制器回家而另一部分作为动作

$.post("@Url.Action("getInfoAboutChecked", "Home")", JSON.stringify(postIds.data));

你的控制器需要一个字符串数组,你发送的是一个对象,其属性是一个字符串数组
同样使用$.post你可以发送一个简单的对象来序列化它而不是数组,所以你必须使用JSON.stringify

答案 1 :(得分:0)

可能有一种更好的方法可以做到这一点(我对JavaScript很新),但事实上我昨晚编写了一种功能性的方法:

var opts = "";
$('#myForm input:checked').each(function (i, elem) {
    opts += this.value + ",";
});
var ajaxUrl = myUrl + "&opts=" + opts;

在控制器中我需要一个参数string ops。在控制器中,我将字符串拆分为“,”以获取各个值。

<强>更新

您的帖子可以像这样更新HTML:

$.post("/Home/getInfoAboutChecked", postIds, function(data) {
  $('#idOfDivWhereResultShouldGo').html(data);
});