2017-09-06 28 views
0

我想通過在我的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; 
    } 
+1

爲什麼你使用'@ Html.Action()'這個?爲什麼不使用調用返回'JsonResult'的方法的ajax? –

+1

'$ .ajax'用'success'調用'JsonResult'部分應該沒問題。 'Html.Action'旨在用於返回整個視圖或部分視圖而不是JSON的操作方法。 –

+1

還有一種方法:將值作爲模型或ViewBag中的列表屬性。然後在你的cshtml中循環並填充一個javascript數組:'' – adiga

回答

1

那麼從目前尚不清楚是什麼錯誤,或者到底發生了什麼,但我看到一對夫婦的問題。我建議爲了修復代碼如下:

1)控制器方法的結果更改爲JsonResult:

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

2)讓您通過Ajax調用記事本的數據(:你需要插入在HTTP格式正確的URL的Http.Action /剃刀不會在JavaScript工作):

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

感謝您的評論以及對我的文章的評論,我對mvc還是有點新鮮感,並且剛剛在整個地方使用動作來調用函數,以便更好地學習一些東西並改進它們。 –