【发布时间】:2017-09-06 06:43:38
【问题描述】:
我试图通过在我的 MVC 控制器中调用一个函数并传回一个字符串数组来在 javascript 中创建一个字符串数组。这简直就是行不通,我不确定我需要做些什么来修改它。下面你可以看到我的 javascript 和控制器代码。非常感谢任何帮助
javascript:
var optionString = @Html.Action("PopulateDashboardDropdown", "Embed", new { Dashboards = Model[0][0].Dashboards });
控制器:
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;
}
【问题讨论】:
-
你为什么要使用
@Html.Action()?为什么不直接使用调用返回JsonResult的方法的ajax? -
$.ajax用JsonResult调用success部分应该没问题。Html.Action旨在与返回整个视图或部分视图的操作方法一起使用,而不是 JSON。 -
还有另一种方法:在模型或
ViewBag中将值作为列表属性获取。然后在您的 cshtml 中循环并填充一个 javascript 数组:<script> var optionArray = []; @foreach (var i in Model.YourList) { @:optionArray.push(@i); } </script>
标签: javascript c# arrays asp.net-mvc razor