SharePoint 2010: создайте кнопку закладки, которая добавляет страницу к вашим ссылкам - PullRequest
2 голосов
/ 10 февраля 2011

Я пытаюсь создать ссылку / кнопку на моей главной странице, которая при нажатии добавляет текущую страницу в список Мои ссылки пользователя.Это всего лишь ярлык, чтобы избавить пользователя от необходимости переходить на Мой сайт и добавлять ссылку вручную.

[Этот пост в блоге] дает решение дляэта проблема, но я получаю ошибку JavaScript во второй строке диалогового окна «Добавить ссылку» (QuickLinksDialog2.aspx), поскольку свойство frameElement имеет значение null:

<script language="Javascript">
    var form = document.forms[0];
    var args = window.parent.frameElement.dialogArgs;

Независимо от того, Portal.js , по-видимому, содержит все функции, которые страница My Links (_layouts / MyQuickLinks.aspx) использует для добавления ссылок в этот список.

Может кто-нибудь подсказать, как мне поступить при его вызове?/ некоторые из этих функций с моей главной страницы, чтобы открылось диалоговое окно «Добавить ссылку» с предварительно добавленными полями заголовка и URL-адреса?

Ответы [ 2 ]

2 голосов
/ 20 апреля 2011

Добавьте следующую функцию на главную страницу:

function addlink(){
    t=document.title;
    u=escape(location.href);

    var q = window.location.protocol + "//" + window.location.host + "/_vti_bin/portalapi.aspx?cmd=PinToMyPage&ListViewURL=" + u + "&ListTitle=" + t + "&IsDlg-1"; // + "&ReturnUrl=" + u;

    location.href = q;

}

Затем добавьте свой якорный тег:

<a href='javascript:addlink()'>Add this Page</a>
2 голосов
/ 01 марта 2011

В итоге я использовал объектную модель для создания моих ссылок (в соответствии с всплывающим диалоговым окном).

Преимуществом этого является то, что добавление ссылки теперь выполняется только одним нажатием, недостатком является то, что у пользователя нет возможности переименовать ссылку или назначить ее группе (лично яВ любом случае мы скрыли группы от пользовательского интерфейса, так как они нам не нужны, так что это не проблема для меня.Ваша главная страница / макет страницы.Мой код для этого следующий:

HTML


<script type="text/javascript">
    function FavouriteImageButton_AddMyLink_Clicked() {
        SP.UI.Notify.addNotification("Bookmark generated successfully.");
    }

    function FavouriteImageButton_RemoveMyLink_Clicked() {
        SP.UI.Notify.addNotification("Bookmark deleted successfully.");
    }
</script>

<asp:UpdatePanel ID="UpdatePanel" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:ImageButton ID="FavouriteImageButon" runat="server" OnCommand="FavouriteImageButton_Command" />
    </ContentTemplate>
</asp:UpdatePanel>

C #


private struct FavouriteButtonCommandNames
{
    public const string AddMyLink = "AddMyLink";
    public const string RemoveMyLink = "RemoveMyLink";
}

protected void Page_PreRender(object sender, EventArgs e)
{
    // Initialise the favourites button according to whether or not the page already exists in the My Links list.
    this.FavouriteImageButon.ImageUrl = "/_layouts/images/favourite_add.png";
    this.FavouriteImageButon.AlternateText = "Add to My Links";
    this.FavouriteImageButon.CommandName = FavouriteButtonCommandNames.AddMyLink;
    this.FavouriteImageButon.CommandArgument = null;

    UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.Current);
    UserProfile currentUser = userProfileManager.GetUserProfile(false);

    foreach (QuickLink quickLink in currentUser.QuickLinks.GetItems())
    {
        if (quickLink.Url.ToLower() == this.Page.Request.Url.ToString().ToLower())
        {
            this.FavouriteImageButon.ImageUrl = "/_layouts/images/favourite_delete.png";
            this.FavouriteImageButon.AlternateText = "Remove from My Links";
            this.FavouriteImageButon.CommandName = FavouriteButtonCommandNames.RemoveMyLink;
            this.FavouriteImageButon.CommandArgument = quickLink.ID.ToString();
            break;
        }
    }
}

protected void FavouriteImageButton_Command(object sender, CommandEventArgs e)
{
    UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.Current);
    UserProfile currentUser = userProfileManager.GetUserProfile(false);

    switch (e.CommandName)
    {
        case FavouriteButtonCommandNames.AddMyLink:
            // Create the link.
            currentUser.QuickLinks.Create(
                SPContext.Current.File.Title, 
                this.Page.Request.Url.ToString(), 
                QuickLinkGroupType.General, 
                null, 
                Privacy.Private);

            // Display a notification message.
            ScriptManager.RegisterStartupScript(this.UpdatePanel, this.UpdatePanel.GetType(), e.CommandName, "ExecuteOrDelayUntilScriptLoaded(FavouriteImageButton_AddMyLink_Clicked, \"sp.js\");", true);
            break;

        case FavouriteButtonCommandNames.RemoveMyLink:
            long id;

            if (long.TryParse((string)e.CommandArgument, out id))
            {
                // Delete the link.
                QuickLink quickLink = currentUser.QuickLinks[long.Parse((string)e.CommandArgument)];
                quickLink.Delete();

                // Display a notification message.
                ScriptManager.RegisterStartupScript(this.UpdatePanel, this.UpdatePanel.GetType(), e.CommandName, "ExecuteOrDelayUntilScriptLoaded(FavouriteImageButton_RemoveMyLink_Clicked, \"sp.js\");", true);
            }
            else
            {
                throw new ArgumentNullException("e.CommandArgument", "\"{0}\" is not a valid QuickLink ID. The QuickLink could not be removed from the list.");
            }
            break;
    }
}
...