考虑使用ObjectDataSource填充GridView的下列Webforms代码:
Default.aspx
<asp:GridView ID="GV" DataSourceID="ODS" runat="server"/>
<asp:ObjectDataSource ID="ODS" TypeName="WebApplication.Default" SelectMethod="GetModels" runat="server" />
<asp:Label ID="Label" runat="server"/>Default.aspx.cs
private static readonly List<Model> Models;
static Default()
{
Models = new List<Model>
{
new Model {Id = 1, Name = "Foo"},
new Model {Id = 2, Name = "Bar"},
new Model {Id = 3, Name = "Foo"},
new Model {Id = 4, Name = "Bar"}
};
}
public List<Model> GetModels()
{
var listsizeCap = 3;
var totalCount = Models.Count;
if (totalCount > listsizeCap)
{
// Label is null!
Label.Text = string.Format("The grid only shows the first {0} results of a total of {1}", listsizeCap, totalCount);
}
return Models.Take(listsizeCap).ToList();
}我需要限制由数据源返回的项目的数量,并显示有多少项被限制了。
但是,当我到达GetModels方法时,Label是空的。
知道如何在ObjectDataSource选择方法中设置控件的值吗?
发布于 2014-09-02 18:15:37
对于所有ASP.NET来说,ObjectDataSource上的TypeName属性引用了一个简单的POCO。在我的例子中,它恰好是Page类。无论如何,当ASP.NET调用GetModels时没有任何页面硬布线,因此其他控件(如Label )不会在幕后初始化。
我通过在HttpContext.Current.Items上添加临时状态找到了一个解决方案。
然后,GetModels变成:
public List<Model> GetModels()
{
var listsizeCap = 3;
var totalCount = Models.Count;
if (totalCount > listsizeCap)
{
HttpContext.Current.Items["LabelToSet"] = string.Format("The grid only shows the first {0} results of a total of {1}", listsizeCap, totalCount);
}
return Models.Take(listsizeCap).ToList();
}Default.aspx被更新为一个OnDataBound事件:
<asp:GridView ID="GV" DataSourceID="ODS" OnDataBound="GV_DataBound" runat="server"/>,它从HttpContext读取值并将其分配给Label。
protected void GV_DataBound(object sender, EventArgs e)
{
Label.Text = HttpContext.Current.Items["LabelToSet"].ToString();
}发布于 2014-09-02 14:52:34
您说的是寻呼数据源吗?如果是这种情况,则只需使用
EnablePaging=“真” SelectCountMethod="“
您在这里声明的方法将返回应由此方法返回的总记录。您需要自己编写此方法,但它应该与选择方法相同。然后你可以使用:
MaximumRowsParameterName="“ StartRowIndexParameterName="“
ObjectDataSource的select方法将使用这些参数,因为它是最后两个参数。如果您在ObjectDataSource中声明变量,则不要实际添加它们,这将自动传递。将这里设置的名称添加到实际的方法减速中。您将根据这些值将选择代码调整为页面。
编辑:保留上面的项目以保持完整性。这个问题的答案应该是以下。
如果使用的是ObjectDataSource的分页方法,则不应尝试更改select方法中的页面元素。您应该分离这个逻辑,并依赖ObjectDataSource的onSelected方法。具体来说,您将获得声明的SelectCountMethod的返回值。然后,您可以将类似的内容添加到页面后面的代码中。
public int recordsReturned;
public int recordCount;
protected void nameOfYourOnSelectedMethod(object sender, ObjectDataSourceStatusEventArgs e)
{
// check if this call is from the Select or SelectCount method
if (e.ExecutingSelectCount) {
// logic here will be used for setting the label
recordCount = e.ReturnValue;
Label.Text = "The grid only shows the first " + recordsReturned.ToString() + " results of a total of " + recordCount.ToString();
}
else {
// logic here is to get the amount of records returned
// you just want to save the value here
recordsReturned = e.ReturnValue.Count();
}我自己还没有尝试过这些代码,但是它应该能工作。
https://stackoverflow.com/questions/25625936
复制相似问题