我是C#的新手,我遇到了一个我无法调用以显示在我的aspx页面上的变量的问题。
背后的代码如下:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
namespace PRIIS
{
public partial class _Default : System.Web.UI.Page
{
private DirectoryEntry GetDirectoryObject()
{
DirectoryEntry oDE;
oDE = new DirectoryEntry("LDAP://192.168.5.4", "user", "xxxx", AuthenticationTypes.Secure);
return oDE;
}
public DirectoryEntry GetUser(string UserName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserName + "))";
deSearch.SearchScope = SearchScope.Subtree;
SearchResult results = deSearch.FindOne();
if (!(results == null))
{
de = new DirectoryEntry(results.Path, "user", "xxxx", AuthenticationTypes.Secure);
return de;
}
else
{
return null;
}
}
public class MyUserName
{
public string strName;
public string str;
public void userNameOnSystem()
{
strName = HttpContext.Current.User.Identity.Name.ToString();
string[] splitString = strName.Split('\\');
str = splitString[1];
}
}
protected void Page_Load(object sender, EventArgs e)
{
DirectoryEntry de = GetUser("dramirez");
if (de != null)
{
string displayUser = de.Properties["displayName"].Value.ToString();
Response.Write(displayUser + "<br/>");
//Response.Write(de.Properties["telephoneNumber"].Value.ToString() + "<br/>");
//Response.Write(de.Properties["mail"].Value.ToString() + "<br/>");
//Response.Write(de.Properties["userPrincipalName"].Value.ToString() + "<br/>");
}
}
}
}
我正在进行的调用是使用以下语句在.aspx页面上显示的displayUser字符串
<%= displayUser %>
不幸的是我收到了错误;
错误2当前上下文中不存在名称“displayUser”
我不确定问题的来源和来源。
提前感谢您的帮助。
答案 0 :(得分:3)
为了以这种方式从ASPX标记中访问值,它应该是代码隐藏中的属性(至少protected
访问,我相信)。像这样:
protected string DisplayUser { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
DirectoryEntry de = GetUser("dramirez");
if (de != null)
{
DisplayUser = de.Properties["displayName"].Value.ToString();
}
}
然后它应该显示:
<%= DisplayUser %>
答案 1 :(得分:0)
将您的变量声明为Public。
public string displayUser;
protected void Page_Load(object sender, EventArgs e)
{
DirectoryEntry de = GetUser("dramirez");
if (de != null)
{
displayUser = de.Properties["displayName"].Value.ToString();
Response.Write(displayUser + "<br/>");
//Response.Write(de.Properties["telephoneNumber"].Value.ToString() + "<br/>");
//Response.Write(de.Properties["mail"].Value.ToString() + "<br/>");
//Response.Write(de.Properties["userPrincipalName"].Value.ToString() + "<br/>");
}
}