在Sharepoint 2013中将用户控件添加到Web部件

4tu*_*ler 13 sharepoint user-controls web-parts sharepoint-2013

我有一个可视化的Web部件(使用标准的Visual Stuido 2012模板从"添加新项目"表单创建)只有一个<div id="newsListDiv" runat="server"></div>元素.我想使用以下代码以编程方式将自己的用户控件添加到它:

protected void Page_Load(object sender, EventArgs e)
{    
    NewsLine newsLine = Page.LoadControl(@"~/_ControlTemplates/MainTheme/NewsLine.ascx") as NewsLine;
    newsListDiv.Controls.Add(newsLine);
}
Run Code Online (Sandbox Code Playgroud)

但是当我部署解决方案并将Web部件添加到页面时,它会显示一个错误页面,告诉我文件'/_ControlTemplates/MainTheme/NewsLine.ascx'不存在.但是,如果我查看文件夹"C:\ Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\CONTROLTEMPLATES\MainTheme",我可以看到该文件存在于那里.我试图将信任级别设置为"完全",但得到了相同的错误.我也尝试在.ascx文件中添加用户控件,如下所示:

<%@ Register Src="~/_controltemplates/MainTheme/NewsLine.ascx" TagPrefix="uc1" TagName="NewsLine" %>

<div id="newsListDiv" runat="server">
    <uc1:NewsLine runat="server" id="NewsLine" />
</div>
Run Code Online (Sandbox Code Playgroud)

这样就得到了编译错误:"当前上下文中不存在名称'InitializeControl'".我也注意到,只要我将注册或参考行(带有我的用户控件的路径)添加到我的.ascx文件,.g.cs文件就会变成空白!当我删除该行时,它会再次填满.我尝试了许多不同的路径着作,如"../_controltemplates/","/ controltemplates/15 /"等.但它们都没有任何区别.我在这里绝望,请帮忙!

小智 19

你忘了再试一次.访问_layouts文件夹时也是如此.你应该指定15个蜂巢.

正确的路径是"〜/ _ControlTemplates/15

 NewsLine newsLine = Page.LoadControl(@"~/_ControlTemplates/15/MainTheme/NewsLine.ascx") 
Run Code Online (Sandbox Code Playgroud)