javascript - 使用 Html.action 在 javascript 中创建数组

标签 javascript c# arrays asp.net-mvc razor

我试图通过调用 MVC Controller 中的函数并传回字符串数组来在 javascript 中创建字符串数组。这根本不起作用,我不确定我需要做什么来修改它。下面你可以看到我的 javascript 和 Controller 代码。非常感谢任何帮助

JavaScript:

var optionString = @Html.Action("PopulateDashboardDropdown", "Embed", new { Dashboards = Model[0][0].Dashboards });

Controller :

public string[] PopulateDashboardDropdown(ODataResponseListDashboard[] dashboards)
    {
        string email = "";
        //loop that finds the groupID assigned to the currently logged in user
        foreach (Claim claim in ClaimsPrincipal.Current.Claims)
        {
            if (claim.Type == "emails")
            {
                email = claim.Value;
                email = email.ToLower();
            }
        }
        string[] orgs = GetOrgs(email);
        string[] retVal = new string[orgs.Length];
        bool[] admin = new bool[orgs.Length];
        for (int i = 0; i < orgs.Length; i++)
        {
            admin[i] = isAdmin(orgs[i], email);
            retVal[i] = "";
        }

        //loop that creates a string to emulate the innerHtml of a dropdown selector based on the names of all dashboards in the workspace
        for (int i = 0; i < orgs.Length; i++)
        {
            for (int j = 0; j < dashboards[i].Value.Count; j++)
            {
                if (dashboards[i].Value.ElementAtOrDefault(j).DisplayName.Contains("Admin"))
                {
                    if (admin[i])
                    {
                        retVal[i] += "<option>" + dashboards[i].Value.ElementAtOrDefault(j).DisplayName + "</option>";
                    }
                }
                else
                {
                    retVal[i] += "<option>" + dashboards[i].Value.ElementAtOrDefault(j).DisplayName + "</option>";
                }
            }
        }
        return retVal;
    }

最佳答案

嗯,不清楚错误是什么或到底发生了什么,但我看到了一些问题。我建议执行以下操作来修复代码:

1) 将 Controller 方法的结果更改为 JsonResult:

public JsonResult PopulateDashboardDropdown(ODataResponseListDashboard[] dashboards)
{
    ...
    return this.Json(retVal);
}

2) 通过 ajax 调用获取数据(注意:您需要以 http 格式插入正确的 url。Http.Action/Razor 在 javascript 中不起作用):

$.getJSON(myUrl, function (data) {  
   var optionString = data;       
   ...
});

关于javascript - 使用 Html.action 在 javascript 中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46068498/

相关文章:

php - jQuery Ajax 请求仅适用于单个表单提交

c# - 如何调试 Roslyn 编译生成的 dll?

c# - WPF 项目不支持 Canvas ?

java - 扩展 File 类时出现 ClassCastException 问题

c - jni - 将 int[][] 转换为 jobjectArray 并将其返回给 java

javascript - HTML Javascript 幻灯片优化

javascript不想解析文本超过两次

c# - Windows 窗体应用程序命令行参数

Javascript按时间倒序对对象数组进行排序

javascript - 追加后获取文本框值 - jQuery