【问题标题】:create array in javascript with Html.action使用 Html.action 在 javascript 中创建数组
【发布时间】: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 数组:&lt;script&gt; var optionArray = []; @foreach (var i in Model.YourList) { @:optionArray.push(@i); } &lt;/script&gt;

标签: javascript c# arrays asp.net-mvc razor


【解决方案1】:

好吧,from 不清楚是什么错误或究竟发生了什么,但我看到了几个问题。我建议以下以修复代码:

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;       
   ...
});

【讨论】:

  • 感谢这篇文章和我帖子中的 cmets 我对 mvc 还有些陌生,并且刚刚在各处使用 action 来调用函数,学习更多知识和改进东西真是太好了。
猜你喜欢
  • 2011-05-27
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 2023-01-26
  • 2019-04-05
  • 1970-01-01
  • 2015-12-13
相关资源
最近更新 更多