我有一个div:<div id="txtContactFirstPrint"></div>
我希望在页面加载时在codebehnd中运行一个查询,用数据库中的值填充div。但不确定如何。
这是我在codebehind中的查询:
public partial class print_request : System.Web.UI.Page
{
public static object getProjectByID(int id)
{
using (dbPSREntities11 myEntities = new dbPSREntities11())
{
var thisProject = myEntities.tbProjects.Where(x => x.ProjectID == id);
var columns = thisProject.Select(x => new { x.ProjectContactFirstName, x.ProjectContactLastName, x.refDepartmentID, x.refAuthSignerID, x.ProjectAccountNum, x.ProjectContactInfo, x.refBuildingID, x.ProjectRoomNum, x.ProjectWorkType, x.ProjectDescription, x.ProjectManagerID, x.MaintenanceAccount, x.StartDate, x.ProjectContactEmail }).ToList();
return columns;
}
}
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["id"].ToString();
getProjectByID(Convert.ToInt32(id));
txtContactFirstPrint.InnerHtml = getProjectByID.ProjectContactFirstName.ToString(); <---- I've been doing trial and error, but it's SOMETHING like this. Hope I'm close...
}
}
知道我应该如何使用数据库中的值填充div?谢谢!
答案 0 :(得分:0)
我会做一些改变:
getProjectByID()
应返回单个对象或对象列表。在你的情况下,我会返回单个对象:
public static tbProject getProjectByID(int id)
{
using (dbPSREntities11 myEntities = new dbPSREntities11())
{
return myEntities.tbProjects.Where(x => x.ProjectID == id).FirstOrDefault();
}
}
我会在标记中创建Div
'runat =“server”`:
<div id="myDiv" runat="server"></div>
在代码中这样做:
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["id"].ToString();
var myResult = getProjectByID(Convert.ToInt32(id));
if(myResult != null)
{
myDiv.InnerHtml = myResult.ProjectContactFirstName;
}
}
如果您想要显示多条记录,getProjectByID()
应该返回List<tbProject>
。在Page_load中,您必须循环遍历列表中的每个tbProject
并附加到字符串。完成循环后,将字符串附加到div。
BTW: getProjectByID()
需要public static
吗?我建议将其设为private
或protected
。