用C#插入<p>标签?</p>

时间:2014-03-14 18:13:51

标签: c# html insert

这是一个奇怪的问题,但有没有办法在某些导入的文本周围插入<p>标签?我有一个博客条目列表,每个条目都来自它自己的来源(我认为它是Sitecore的复制粘贴工作)。所有参赛作品都有&#34;简介&#34;这是关于文章的模糊。其中一些标签包含<p>标签而其他标签没有(我不确定为什么,我无法更改源材料 - 我只能控制它的外观如何到来进入博客列表页面)我认为应该检查一下它们是否确实存在,尽管我不确定如何做到这一点。

这是博客列表的前端:

<asp:GridView ID="EntryList" runat="server" OnItemDataBound="EntryDataBound" AllowPaging="true" PageSize="3" AutoGenerateColumns="false" EnablePersistedSelection="true" DataKeyNames="EntryID" OnPageIndexChanging="grdTrades_PageIndexChanging" GridLines="None" PagerSettings-Position="TopAndBottom" CssClass="mGrid" pagerstyle-cssclass="pagination" rowstyle-cssclass="norm" alternatingrowstyle-cssclass="altColor" width="100%">
 <Columns>
 <asp:TemplateField>
        <ItemTemplate>
<li class="wb-entry-list-entry" >
    <div class="imgOuter">
        <div class="imgInner">
            <asp:Image runat="server" ID="EntryImage" CssClass="wb-image" ImageUrl='<%# Eval("Image") %>' />
        </div>
    </div>
    <div class="outer">
        <div class="wb-entry-detail" >
            <h2>
                <a href="<%# Eval("EntryPath") %>"><%# Eval("Title") %></a>
            </h2>
            <div class="wb-details">
                <%# Eval("EntryDate") %>
                <%# Eval("Author") %><br />
                <%# Eval("AuthorTitle") %>
            </div>

            <%# Eval("Introduction") %>

            <asp:HyperLink ID="BlogPostLink" runat="server" CssClass="wb-read-more" NavigateUrl='<%# Eval("EntryPath") %>'><%# Sitecore.Globalization.Translate.Text("READ_MORE")%></asp:HyperLink>
            <asp:PlaceHolder ID="CommentArea" runat="server">
                <span class="wb-comment-count">

                </span>
            </asp:PlaceHolder>
        </div>
    </div>
</li>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
    <%#Sitecore.Globalization.Translate.Text("NO_POSTS_FOUND")%>
</EmptyDataTemplate>

这就是代码隐藏:

Database db = Sitecore.Context.Database;
protected const string DEFAULT_POST_TEMPLATE = "/layouts/WeBlog/PostListEntry.ascx";
protected Size m_imageMaxSize = Size.Empty;

protected void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
    EntryList.PageIndex = e.NewPageIndex;
    string tag = Request.QueryString["tag"];
    BindEntries(tag);
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string requestedToShowStr = Request.QueryString["count"] ?? "0";
        int requestedToShow = 0;
        int.TryParse(requestedToShowStr, out requestedToShow);
        string startIndexStr = Request.QueryString["startIndex"] ?? "0";
        int startIndex = 0;
        int.TryParse(startIndexStr, out startIndex);
        string tag = Request.QueryString["tag"];
        Item CurrentItem = Sitecore.Context.Item;
        BindEntries(tag);
        string blogUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item);
    }
}

protected void BindEntries(string tag)
{
    DataSet ds = new DataSet();
    DataTable ResultTable = ds.Tables.Add("EntryTable");
    ResultTable.Columns.Add("EntryID", Type.GetType("System.String"));
    ResultTable.Columns.Add("EntryPath", Type.GetType("System.String"));
    ResultTable.Columns.Add("Title", Type.GetType("System.String"));
    ResultTable.Columns.Add("EntryDate", Type.GetType("System.String"));
    ResultTable.Columns.Add("Author", Type.GetType("System.String"));
    ResultTable.Columns.Add("AuthorTitle", Type.GetType("System.String"));
    ResultTable.Columns.Add("Introduction", Type.GetType("System.String"));
    ResultTable.Columns.Add("Image", Type.GetType("System.String"));

    Item CurrentItem = Sitecore.Context.Item;
    Item BlogStart = ScHelper.FindAncestor(CurrentItem, "BlogHome");
    Item[] EntryArray = null;

    if (tag == "")
        EntryArray = BlogStart.Axes.SelectItems(@"child::*[@@templatename='Folder']/*[@@templatename='Folder']/*[(@@templatename='BlogEntry' ) ]");
    else
        EntryArray = BlogStart.Axes.SelectItems(@"child::*[@@templatename='Folder']/*[@@templatename='Folder']/*[(@@templatename='BlogEntry' and contains(@tags,'" + tag + "' )) ]");

    ArrayList PostList = new ArrayList();
    if (EntryArray != null)
    {
        foreach (Item EntryItem in EntryArray)
        {
            if (EntryItem.Fields["Post Date"].Value != "")
            {
                BlogEntryProcessor.BlogEntrys obj1 = new BlogEntryProcessor.BlogEntrys();
                obj1.Description = EntryItem.Fields["Introduction"].Value;
                obj1.Guid = EntryItem.ID.ToString();
                obj1.Link = ScHelper.GetPath(EntryItem);
                obj1.PostDate = formatDateCmp(EntryItem.Fields["Post Date"].Value);
                obj1.Title = EntryItem.Fields["Title"].Value;
                PostList.Add(obj1);
            }
        }
        PostList.Sort();
        PostList.Reverse();

        foreach (BlogEntryProcessor.BlogEntrys obj in PostList)
        {
            DataRow dr = ResultTable.NewRow();
            Item BlogEntry = db.Items[obj.Guid];
            dr["EntryID"] = obj.Guid;
            dr["EntryPath"] = ScHelper.GetPath(BlogEntry);
            dr["Title"] = BlogEntry.Fields["Title"].Value;
            dr["EntryDate"] = GetPublishDate(BlogEntry);
            dr["Author"] = GetAuthor(BlogEntry);
            dr["AuthorTitle"] = GetAuthorTitle(BlogEntry);
            dr["Introduction"] = BlogEntry.Fields["Introduction"].Value;
            //TODO: get Default Image
            string EntryThumbImage = BlogEntry.Fields["Thumbnail Image"].Value;
            string EntryImage = BlogEntry.Fields["Image"].Value;
            string ArtImage = "http://fpoimg.com/140x140";
            if (EntryImage != "")
            {
                Sitecore.Data.Fields.XmlField fileField = BlogEntry.Fields["Image"];
                ArtImage = "/" + ScHelper.GetCorrectFilePath(fileField);
            }
            else if (EntryThumbImage != "")
            {
                Sitecore.Data.Fields.XmlField fileField = BlogEntry.Fields["Thumbnail Image"];
                ArtImage = "/" + ScHelper.GetCorrectFilePath(fileField);
            }
            dr["Image"] = ArtImage;
            ResultTable.Rows.Add(dr);
        }
        EntryList.DataSource = ds;
        EntryList.DataMember = "EntryTable";
        EntryList.DataBind();
    }
}

protected string GetAuthorTitle(Item entry)
{
    string OutName = "";
    string AuthorID = entry.Fields["Author"].Value;
    Item AuthorItem = db.Items[AuthorID];
    if (AuthorItem != null)
        OutName = AuthorItem.Fields["Author Title"].Value;
    return OutName;
}

protected string GetAuthor(Item entry)
{
    string OutName = "";
    string AuthorID = entry.Fields["Author"].Value;
    Item AuthorItem = db.Items[AuthorID];
    if (AuthorItem != null)
        OutName = string.Format("<br />By <a href='{0}'>{1}</a>", ScHelper.GetPath(AuthorItem), AuthorItem.Fields["Author Name"].Value);
    return OutName;
}

protected string GetPublishDate(EntryItem CurrentEntry)
{
    string pDate = GOJOHelper.FormatDate(((Item)CurrentEntry).Fields["Post Date"].Value);
    return pDate;
}

protected void EntryDataBound(object sender, ListViewItemEventArgs args)
{
    if (args.Item.ItemType == ListViewItemType.DataItem)
    {
        var dataItem = args.Item as ListViewDataItem;
        var control = dataItem.FindControl("EntryImage");
        if (control != null)
        {
            var imageControl = control as global::Sitecore.Web.UI.WebControls.Image;
            imageControl.MaxWidth = m_imageMaxSize.Width;
            imageControl.MaxHeight = m_imageMaxSize.Height;
            var entry = dataItem.DataItem as EntryItem;
            if (entry.ThumbnailImage.MediaItem == null)
                imageControl.Field = "Image";
        }
    }
}

//string to use to sort the dates - must have 2 digit for month and day
private string formatDateCmp(string date)
{
    // Set the dateResult for the TryParse
    DateTime dateResult = new DateTime();
    // Split the date up.  ie. 20090101T000000
    string[] TempStr = date.Split('T');
    // Set the date to the characters before the T
    date = TempStr[0];
    // Insert a slash after the first 4 characters and after 7 
    date = date.Insert(4, "/").Insert(7, "/");
    return date;
}

2 个答案:

答案 0 :(得分:1)

你可以随时做......

dr["Introduction"] = BlogEntry.Fields["Introduction"].Value
                              .Replace("\n\n", "</p><p>");

...或者使用哪个转义字符来表示源数据中段落的分隔。或者,您可以使用Regex实用程序。有关进一步的参考,请参见示例3 in this article

答案 1 :(得分:0)

首先在你的GridView中你有

OnItemDataBound="EntryDataBound"

OnItemDataBound不是GridView的事件我觉得有点惊讶!

使用

OnRowDataBound="EntryList_RowDataBound"

这是我对GridView和Repeater的常见模式,注意到我在HTML中使用了Literal控件,我不是Eval的超级粉丝!另请注意if (dataItem == null),如果该行有数据项,RowTypes(如页眉和页脚)没有任何数据,则比典型的if(e.Row.RowType == DataControlRowType.Header)等更容易

<asp:GridView ID="EntryList" runat="server" OnRowDataBound="EntryList_RowDataBound" AllowPaging="true" PageSize="3" AutoGenerateColumns="false" EnablePersistedSelection="true" DataKeyNames="EntryID" OnPageIndexChanging="grdTrades_PageIndexChanging" GridLines="None" PagerSettings-Position="TopAndBottom" CssClass="mGrid" PagerStyle-CssClass="pagination" RowStyle-CssClass="norm" AlternatingRowStyle-CssClass="altColor" Width="100%">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <li class="wb-entry-list-entry">
                            <div class="imgOuter">
                                <div class="imgInner">
                                    <asp:Image runat="server" ID="EntryImage" CssClass="wb-image" ImageUrl='<%# Eval("Image") %>' />
                                </div>
                            </div>
                            <div class="outer">
                                <div class="wb-entry-detail">
                                    <h2>
                                        <a href="<%# Eval("EntryPath") %>"><%# Eval("Title") %></a>
                                    </h2>
                                    <div class="wb-details">
                                        <%# Eval("EntryDate") %>
                                        <%# Eval("Author") %><br />
                                        <%# Eval("AuthorTitle") %>
                                    </div>

                                    <asp:Literal runat="server" ID="IntroductionLiteral"/>

                                    <asp:HyperLink ID="BlogPostLink" runat="server" CssClass="wb-read-more" NavigateUrl='<%# Eval("EntryPath") %>'><%# Sitecore.Globalization.Translate.Text("READ_MORE")%></asp:HyperLink>
                                    <asp:PlaceHolder ID="CommentArea" runat="server">
                                        <span class="wb-comment-count"></span>
                                    </asp:PlaceHolder>
                                </div>
                            </div>
                        </li>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EmptyDataTemplate>
                <%#Sitecore.Globalization.Translate.Text("NO_POSTS_FOUND")%>
            </EmptyDataTemplate>
        </asp:GridView>

.cs文件

protected void EntryList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        var dataItem = e.Row.DataItem as EntryItem;
        if (dataItem == null)
            return;

        var imageControl = e.Row.FindControl("EntryImage") as global::Sitecore.Web.UI.WebControls.Image;
        var introductionControl = e.Row.FindControl("IntroductionLiteral") as Literal;
        if (imageControl == null || introduction == null)
            return;

        imageControl.MaxWidth = m_imageMaxSize.Width;
        imageControl.MaxHeight = m_imageMaxSize.Height;

        if (dataItem.ThumbnailImage.MediaItem == null)
            imageControl.Field = "Image";

        if (!string.IsNullOrEmpty(data["introduction"]))
            introductionControl.Text = string.Format("<p>{0}</p>", data["introduction"].ToString().Replace("\n\r", "</p><p>"));
    }

此外,如果您有一个Sitecore对象列表,为什么不将它绑定到GridView,然后在您的RowDataBound方法中获取该项目

var dataItem = e.Row.DataItem as Item;

然后在那里的BindEntries方法中执行逻辑,可能是更干净的代码,您不必使用愚蠢的DataSet!只是一个想法。