【问题标题】:Knockout js external template from a MVC Controller来自 MVC 控制器的 Knockout js 外部模板
【发布时间】:2013-01-26 01:11:28
【问题描述】:

我有一个 Knockout js viewModel,想使用外部模板来获取一个 MVC 4 razor (cshtml) 绑定页面,以便可以在服务器上创建初始页面或通过 Knockout 绑定,我将在运行时决定。我想像这样将模板的名称传递给控制器​​(/Templates/KnockoutTemplate?templateName='gauge'),其中“gauge”是视图的名称(radial.tmpl.cshtml),并让 Knockout 将其放入模板块。

我的控制器:

public class TemplatesController : Controller
{
     public TemplatesViewModel viewModel { get; set; }
     public TemplatesController()
     {
        this.viewModel = new TemplatesViewModel { Heading = "Radial" };
     }

    public ActionResult KnockoutTemplate(string templateName)
    {
        // is this right?
        return  PartialView(templateName, this.viewModel);
    }
}

radial.cshtml

   @model MVC4.Models.TemplatesViewModel
    @{
        ViewBag.Title = "Radial Template";
    }
    <div id="radialDashboardWidget" class="dashboardWidget" style="width: 100%">
     <h4 class="bold">@Model.Heading </h4>
     <!-- or I can do this, I'll decide at development time  -->
     <h4 class="bold" data-bind="text:heading"></h4>
    </div>

主页

<div id="dashboardWidgets" data-bind="foreach: Widgets" class="flexible-widget">
 <!-- ko template: {name: Properties.templateName  } -->
 <!-- /ko -->
 <div class="clear" />
</div>

【问题讨论】:

    标签: asp.net-mvc knockout.js


    【解决方案1】:

    我在这里回答了这个问题:http://geekswithblogs.net/Aligned/archive/2012/08/17/knockout-js-and-external-mvc-cshtml-templates.aspx

    我的控制器:

    public class TemplatesController : Controller
    {
        public TemplatesViewModel viewModel { get; set; }
    
        public ActionResult KnockoutTemplate(string templateName)
        {
            return  PartialView(templateName.Replace("/", string.Empty), this.viewModel);
        }
    }
    

    radial.cshtml

    @model MVC4.Models.TemplatesViewModel
    @{
        ViewBag.Title = "Radial Template";
    }
    
    <div id="radialDashboardWidget" class="dashboardWidget" style="width: 100%">
        <h4 class="bold" data-bind="text:@Model.Heading"></h4>
        <!-- add more HTML -->
    </div>
    

    带有 Knockout 的仪表板页面

    <div id="dashboardWidgets" data-bind="foreach: Widgets" class="flexible-widget">
        <!-- ko template: {name: Properties.templateName  } -->
        <!-- /ko -->
        <div class="clear" />
    </div>
    

    【讨论】:

      【解决方案2】:

      不确定您想要实现什么。在您的 cshtml 中,您“绑定”了服务器端模型对象,而不是客户端 JavaScript 对象的可观察属性。你没有在那里使用 Knockout。请发布获取 Widgets-object 的 Javascript,以便我们为您提供帮助。

      【讨论】:

      • 谢谢,我对其进行了编辑以使其更清晰。我希望能够使用任何一种方法,并且仍然使用 KO 的外部模板库加载模板。我有前进的道路,我只需要绕过博客,我会在此处添加链接。
      猜你喜欢
      • 1970-01-01
      • 2016-06-24
      • 2013-01-13
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多