如何从 webpart 中的页面获取对 webpart 中自定义设置的引用?
How to get a reference to custom settings in webpart from a page within webpart?
我创建了一个 Web 部件,然后我创建了第二个将呈现自定义的 .cs 页面 html。它基本上只是一个显示图像的简单页面。但是在第二个 .cs 页面中,我需要访问 Web 部件中的自定义设置。单击辅助页面的 link 时,如何访问主 Web 部件中的自定义工具窗格设置?
第二页是从 VS 2010 生成的,位于布局文件夹中,如下所示:
public partial class GetFile : LayoutsPageBase
{
我想我必须从 Web 部件继承一些东西才能做到这一点,但真的不确定如何做?
您可以使用 SPLimitedWebPartManager
class 访问 Web 部件属性,方法是阅读 Web 部件集合及其在页面上的属性,如下所示,
var web = SPContext.Current.Web;
var currentPageURL = "//URL of the page on which the Web part is present";
var page = web.GetFile(currentPageURL);
using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
var webPartList = from System.Web.UI.WebControls.WebParts.WebPart webPart in webPartManager.WebParts select webPart;
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in webPartList.ToList())
{
if (webPart.Title.ToLower() == "//Name of the web part for which you want to read the properties")
{
PropertyInfo[] wptProperties = webPart.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in wptProperties)
{
if (property.Name == "//Name of the web property which you want to get")
{
// Following code updates the web part property, you can also read it
property.SetValue(webPart, "value to be set", null);
webPartManager.SaveChanges(webPart);
break;
}
}
}
}
Response.Redirect(currentPageURL);
}
finally
{
webPartManager.Web.Dispose();
}
}
我创建了一个 Web 部件,然后我创建了第二个将呈现自定义的 .cs 页面 html。它基本上只是一个显示图像的简单页面。但是在第二个 .cs 页面中,我需要访问 Web 部件中的自定义设置。单击辅助页面的 link 时,如何访问主 Web 部件中的自定义工具窗格设置?
第二页是从 VS 2010 生成的,位于布局文件夹中,如下所示:
public partial class GetFile : LayoutsPageBase
{
我想我必须从 Web 部件继承一些东西才能做到这一点,但真的不确定如何做?
您可以使用 SPLimitedWebPartManager
class 访问 Web 部件属性,方法是阅读 Web 部件集合及其在页面上的属性,如下所示,
var web = SPContext.Current.Web;
var currentPageURL = "//URL of the page on which the Web part is present";
var page = web.GetFile(currentPageURL);
using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
var webPartList = from System.Web.UI.WebControls.WebParts.WebPart webPart in webPartManager.WebParts select webPart;
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in webPartList.ToList())
{
if (webPart.Title.ToLower() == "//Name of the web part for which you want to read the properties")
{
PropertyInfo[] wptProperties = webPart.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in wptProperties)
{
if (property.Name == "//Name of the web property which you want to get")
{
// Following code updates the web part property, you can also read it
property.SetValue(webPart, "value to be set", null);
webPartManager.SaveChanges(webPart);
break;
}
}
}
}
Response.Redirect(currentPageURL);
}
finally
{
webPartManager.Web.Dispose();
}
}