【问题标题】:how to send Javascript string array to controller and render PartialView如何将 Javascript 字符串数组发送到控制器并渲染 PartialView
【发布时间】:2013-02-09 08:24:49
【问题描述】:

我有这个问题。

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

    checkedItems={"1000","1001","1002"}

  • 我需要将此数组发送到 C# 控制器

  • 当控制器处理完这个数组后,返回 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 中的渲染位置。 感谢帮助

【问题讨论】:

  • 你为什么要定义i?
  • 发帖前有没有检查postIds的值是多少?
  • 在 postIds 中是 Object,其中有数据:array[1] 或 3 或其他,为什么?

标签: javascript ajax jquery asp.net-ajax


【解决方案1】:

可能有更好的方法来做到这一点(我对 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);
});

【讨论】:

  • 但我需要发送整个数组并处理控制器中数组的每个索引并根据结果返回部分视图,但现在我不明白什么是 i 和 elem
  • 你能把你的命令发给我吗?
  • 完美运行,但我如何定义 PartialView 包含(渲染)的位置??
  • 已更新以显示如何使用 PartialView 的输出更新 &lt;div&gt;。
  • 你的意思是 $(something).load(...) 吗?
【解决方案2】:
$.post("/Home/getInfoAboutChecked", JSON.stringify(postIds.data));

您可以使用@Url.Action to 渲染链接,因此假设 home 作为控制器,另一部分作为操作

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

您的控制器需要一个字符串数组,而您发送的是一个具有字符串数组属性的对象
同样使用$.post,您可以发送一个简单的对象并对其进行序列化,但不能发送一个数组,因此您必须使用JSON.stringify

【讨论】:

  • @Url.Action 仅在 .cshtml 文件中有效。最好将 JavaScript 放在单独的 .js 文件中,因为它可以被浏览器缩小和缓存。
  • 不起作用,你确定用括号吗?和我已经包含的 json2.js。 :(
  • 你能验证内容/类型 json 正在发送到服务器吗
  • @ParvSharma:除非另有说明,否则默认内容类型为'application/x-www-form-urlencoded; charset=UTF-8'。如果要发送 Json 并指定匹配的内容类型,请使用 $.ajax({type: 'POST', url: '/Home/getInfoAboutChecked', content-type: 'application/json; charset=utf-8'})
  • @user2080814:不太确定$.getJSON 将如何工作,因为您的操作方法被HttpPost 属性修饰,导致GET 请求无效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多