【问题标题】:Passing values from controller into javascript in mvc5将值从控制器传递到 mvc5 中的 javascript
【发布时间】:2015-02-22 10:12:04
【问题描述】:

我有一个 mvc 视图,它需要显示 twitter 提要。所以在我看来,我有从 twitter 生成的代码。这工作正常。

为了扩展它,我想让它变得有点动态。即我想将data-widget-id="3831079557xxxx" 硬编码为数据库表中的一个值。

以下是 twitter 生成的嵌入推文的 javascript

<div class="row">
   <div class="col-md-12">
      <a class="twitter-timeline" href="https://twitter.com/xxxxx" 
          data-widget-id="3831079557xxxx">Tweets by xxxx</a>
              <script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + "://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } }(document, "script", "twitter-wjs");</script>



                </div>
            </div>

查看模型:

public class homeViewModel
{
    public List<news> newsA { get; set; }

    public List<Rss> feeds { get; set; }

    public List<HomepageSetting> hps { get; set; }

}

Model:这是我可以从中获取 twitter id 的类

public partial class HomepageSetting
    {
        public int Id { get; set; }
        //other properties
        public string Twitter { get; set; }

    }

控制器:

public ActionResult Index()
    {
        homeViewModel hvm = new homeViewModel();
        var data = (from p in db.HomepageSetting where p.ProfileID == Cuser.ProfileId select p);
                hvm.hps= data.ToList();
     return View(hvm);
     }

【问题讨论】:

  • 不清楚的提问方式。我想如果你想得到答案需要更多关于你的问题的描述。

标签: javascript asp.net-mvc-5


【解决方案1】:

在控制器的 Index 方法中,您可以使用 ViewData Dictionary 将 id 传递给视图:

ViewData["id"] = data.id //for example.

在视图中,您可以使用 ViewData["id"] 条目将其分配给 data-widget-id 属性。

<a class="twitter-timeline" href="https://twitter.com/xxxxx" 
          data-widget-id="<%: ViewData["id"] %>">Tweets by xxxx</a>

祝你好运

【讨论】:

  • 您可能想使用 data-widget-id=@ViewData["id"]
  • 它实际上取决于使用的视图引擎。我写的解决方案是针对 ASPX 引擎的。您的解决方案适用于 Razor 引擎。 @Prady
【解决方案2】:

您可以使用 Razor 框架并在 javascript 中拥有

@foreach (var myItem in Request.ServerVariables)
{
    <a class="twitter-timeline" href="https://twitter.com/xxxxx" 
          data-widget-id="3831079557@myItem ">Tweets by xxxx</a>
}

我不能给你更多解释代码,因为这是我在 MVC4 上工作的东西。我不再使用 Microsoft 框架,因此代码将无法完全发挥作用。

也请查看here 以了解 Razor 框架中的更多信息。

【讨论】:

  • 例如,对于Request.ServerVariables,您可以在视图顶部使用名称加载模型,然后在 foreach 循环中调用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2018-02-05
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 2015-11-06
相关资源
最近更新 更多