1

我有一个 asp:hyperlink 控件作为 gridview 模板的一部分。aspx页面中的代码如下:

asp:HyperLink runat="server" ID="lnkEdit" ToolTip="Edit article" NavigateUrl='<%# GetUrl(Eval("ID").ToString(), Eval("CategoryID").ToString()) %>' ImageUrl="~/Images/Edit.gif"

NavigateUrl 值是从代码隐藏方法 GetUrl(string, string) 中获得的。该代码工作正常,如下所示:

protected string GetUrl(string id, string categoryID)
{
    var CategoryID = string.Empty;
    if (!String.IsNullOrEmpty(Request.QueryString["CatID"]))
    {
        CategoryID = Request.QueryString["CatID"].ToString();
    }
    else if (!String.IsNullOrEmpty(categoryID))
    {
        CategoryID = categoryID;
    }
    return "~/TBSArticles/WriteOrEditArticle.aspx?ID=" + id + "&CatID=" + CategoryID;
}

我想通过在 aspx 页面中使用三元运算符来替换方法背后的代码。我尝试了类似下面的方法,但没有奏效:

asp:HyperLink runat="server" ID="lnkEdit" ToolTip="Edit article" NavigateUrl='<%# "~/TBSArticles/WriteOrEditArticle.aspx?ID=" + Eval("ID")  + "&CatID=" + Eval(this.Request.QueryString["CatID"].ToString()) != ""? this.Request.QueryString["CatID"] : Eval("CategoryID")) %>' ImageUrl="~/Images/Edit.gif"
4

2 回答 2

0

The approach you used was cleaner and I prefer that.

I replicated your issue and I think you just have an extra closing bracket

NavigateUrl='<%# "~/TBSArticles/WriteOrEditArticle.aspx?ID=" + Eval("ID")  + "&CatID=" + Eval(this.Request.QueryString["CatID"].ToString()) != ""? this.Request.QueryString["CatID"] : Eval("CategoryID")) %>'

CORRECTION: removed the last Eval("CategoryID") bracket

NavigateUrl='<%# "~/TBSArticles/WriteOrEditArticle.aspx?ID=" + Eval("ID")  + "&CatID=" + Eval(this.Request.QueryString["CatID"].ToString()) != ""? this.Request.QueryString["CatID"] : Eval("CategoryID") %>'
于 2012-06-17T14:23:05.480 回答
0

当你有很多想法时,最好在后面的代码上使用一个函数来调用,并避免因一行代码的困难而产生的问题和错误。因此,您将函数称为:

asp:HyperLink runat="server" NavigateUrl='<%#GetHyperLinkUrl(Container.DataItem)%>' ID="lnkEdit" ToolTip="Edit article" 

并将其写在后面的代码上

protected string GetHyperLinkUrl(object oItem)
{
    StringBuilder cbRet = new StringBuilder();

    cbRet.Append( Page.ResolveUrl("~/TBSArticles/WriteOrEditArticle.aspx?ID=") );
    cbRet.Append( DataBinder.Eval(oItem, "ID") );
    cbRet.Append(  "&CatID=" );

    if(string.IsNullOrEmpty(Request.QueryString["CatID"]))  
        cbRet.Append( DataBinder.Eval(oItem, "CategoryID") );
    else
        cbRet.Append( DataBinder.Eval(oItem, Request.QueryString["CatID"].ToString()) );

    return cbRet.ToString();
}
于 2012-06-17T09:44:56.540 回答