簡體   English   中英

使用Html.action在javascript中創建數組

[英]create array in javascript with Html.action

我試圖通過在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;
    }

好吧,從不清楚是什么錯誤或到底發生了什么,但是我看到了幾個問題。 我建議以下內容以修復代碼:

1)將控制器方法的結果更改為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;       
   ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM