我试图通过调用 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/