views:

46

answers:

1

I don't think this should be in my view, but instead handled by the controller. I suppose this could be done in the SQL (can get ugly real quick) or in the controller (I think this might be best), or maybe even an HTML helper. But, I'm not sure how to unpack/repack my IQueryable/IEnumberable in the controller. I think that giving the template designer everything they need and then some is best, therefore providing both the full description as well as the excerpt (which is generated).

Thoughts/ideas appreciated.

<p>
    <% var description = Regex.Replace(Regex.Replace(spotlight.Description, "<[^>]*>", string.Empty), "[\0x0020\r\n]+", " ").TrimEnd();
        if (description.Length < 297)
        {
        %> <%= description %> <%
        } else { %>
        <%= description.Substring(0, 297) + "..." %> <%
        }                       
    %> <a href="<%= Url.Action("Details", "Spotlights", new { id=spotlight.SpotlightID}) %>">Read &raquo;</a>
</p>

My repository:

    public IQueryable<Spotlight> FindAllSpotlights()
    {
        return from spotlight in db.Spotlights
                   where spotlight.PublishDate <= DateTimeOffset.Now
                   orderby spotlight.PublishDate descending
                   select spotlight;
    }

My controller:

    public ActionResult Index()
    {
        var spotlights = spotlightRepository.FindTopSpotlights().ToList();

        return View(spotlights);
    }
+3  A: 

Suggest keeping your repository as is. Suggest that you extend your Spotlight class to encapsulate all that Regex logic in a property or method.

Extend the behaviour of Spotlight with the nicely formatted description. That'll keep the logic out of your View.

public partial class Spotlight
{
   public string WellFormattedDescription()
   {
     //all the logic to return a well formatted Spotlight.Description
    string desc = Regex.Replace(Regex.Replace(this.Description, "<[^>]*>", 
                                 string.Empty), "[\0x0020\r\n]+", " ")
                       .TrimEnd();

    if (desc.Length < 297)
       return desc;
    else 
       return desc.Substring(0, 297) + "...";
   }
}

Then your View simply calls:

<p>
    <%=spotlight.WellFormattedDescription  %>
    <a href="<%= Url.Action("Details", "Spotlights", new { id=spotlight.SpotlightID}) %>">foo</a>
</p>
p.campbell