我想通過在我的MVC控制器中調用一個函數並傳回一個字符串數組來創建一個JavaScript中的字符串數組。這很簡單,只是不工作,我不知道我需要做些什麼來修改這個。下面你可以看到我的JavaScript和控制器代碼。任何幫助是極大的讚賞在JavaScript中創建數組與Html.action
的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'用'success'調用'JsonResult'部分應該沒問題。 'Html.Action'旨在用於返回整個視圖或部分視圖而不是JSON的操作方法。 –
還有一種方法:將值作爲模型或ViewBag中的列表屬性。然後在你的cshtml中循環並填充一個javascript數組:'' – adiga