【问题标题】:How to fix variable does not exist in current context in SharePoint WebPart code behind?如何修复 SharePoint WebPart 代码后面的当前上下文中不存在变量?
【发布时间】:2016-01-27 13:24:06
【问题描述】:

在为 SharePoint 2010 开发 Web 部件时,我完全是个菜鸟。我创建了一个带有按钮的 Web 部件。单击该按钮时,我希望它将用户重定向到另一个页面。这似乎是一个简单的操作,但我遇到了障碍。

在我的 MyWebPart.ascx.cs 文件中,我有以下代码:

protected void Button_Click(object sender, EventArgs e)
    {
        // Get the values the user inputted
        try
        {
            String category = SearchBySelector.SelectedValue;
            String keyword = SearchField.Text;
            SPWeb root = SPContext.Current.RootWeb.Url;
            String url = root + "/path/to/site.aspx?category=" + category + "&keyword=" + keyword;
            SPUtility.Redirect(url);
        }
        catch (Exception ex)
        {
            StatusLabel.ForeColor = "#FF0000";
            StatusLabel.Text = "Exception encountered." + ex.Message;
        }
    }

我遇到的问题是 SPContext(和 SPUtility)在这种情况下没有被识别。我该如何解决?我想我需要某种包含在某处?我也不是 C# 专家,这可能从我的代码中可以看出。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# visual-studio-2010 sharepoint-2010 web-parts


    【解决方案1】:

    您需要为 SPContext 和 SPUtility 提供完全限定的命名空间,分别为 Microsoft.SharePoint.SPContextMicrosoft.SharePoint.Utilities.SPUtility

    您可以在代码中使用这些完全限定的类名,或者在代码文件的顶部添加两个 using 语句:

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    

    如果 Visual Studio 仍然对您抱怨无法识别这些类型或命名空间,您需要确保将 Microsoft.SharePoint 程序集添加到项目中的引用中。您可以从 Visual Studio 的解决方案资源管理器窗口添加引用。

    【讨论】:

    • 非常感谢您的出色回答。
    猜你喜欢
    • 2013-09-28
    • 2023-03-24
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    相关资源
    最近更新 更多