Implementing “Read More” in .NET with MVC3

2019-08-19 04:49发布

I'm writing a simple "blog" application in .NET with MVC3, as a learning exercise.

To implement - rudimentary - "read more" functionality, I've added a custom button to tiny_mce which, when pressed, inserts

<!--#readmore#-->

into the post content.

The idea is to obtain the content up to that point to show on the homepage and then add a link if there's more to read, as done by every blog engine ever.

Doing this is pretty straightforward, the question I have is where should I do it? Right now, I have the functionality in the Post model:

public String content_read_more()
    {
        if (this.content.Contains("<!--#readmore#-->"))
        {
            int position = this.content.IndexOf("<!--#readmore#-->");
             this.has_read_more = true; 
            return this.content.Substring(0, position);
        }
        else
        {
            this.has_read_more = false;
            return this.content;                 
        }
    }

I avoided creating the link to the complete post within the model, since it didn't seem to be something the Model should do.

But, doing it like that, I have to check if the post has more content in the view:

<div class="content">
    @Html.Raw(item.content_read_more())
    @if (item.hasReadMoreLink())
    {
        @Html.ActionLink("Leer más", "Details", new { id = item.id })
    }
</div>

which introduces logic into the view.

Should I do it in the controller? Is there a better way to do this? Am I thinking about this way too hard?

Thank you!

1条回答
Fickle 薄情
2楼-- · 2019-08-19 05:14

That's perfectly normal.
There is nothing wrong with adding simple ifs in the view.

You should avoid adding business logic in the view; instead, you should put it in the control and send the results to the view (exactly as you're doing now).

查看更多
登录 后发表回答