Question

I am building a blog application using C# MVC5 and EF6. I am using SignalR in a few places, but am now trying to set it up so that users on the homepage (which shows a list of the latest blogs) will automatically have a new blog added to the top if one is added while they're on the page. To do this, I have set up a timer to check the database every 60 seconds to see if a blog has been added since the last check.

//This is called every 60 seconds.
public void CheckForNewBlogs(object state)
{
    //check if there has been a new blogs since last check
    List<BlogViewModel> blogs = blogRepo.GetBlogs().Where(a => a.Created > lastTimeChecked).Select(a => new BlogViewModel(a, user)).ToList();

    lastTimeChecked = DateTime.Now;
    foreach (BlogViewModel blog in blogs)
    {
        BroadcastNewBlog(blog);
    }
}

This is where my problem is, I can create a model for the new blog when there is one, but I can't work out how I then create the partial view to send to the clients via SignalR.

In other cases of using SignalR, it has all been within a Controller and so I have used a PartialViewToString function. Do I have to create an instance of the controller, or is there a better way?

Any help appreciated. Thanks.

Was it helpful?

Solution

I would not push a view through SignalR. I will push an event warning the page that a new blog post exists with a given URL, and then the page can proceed to get that page/view in the usual way.

Also, I would not have a timer to check if there is new stuff in the DB. When a new post is created, as last step in the creation, I will broadcast an event saying that a new posts exists as before.

To push ASP.NET MVC generated view through SignalR, you have to mock a request and go through a lot of trouble that will render useless lot of the ASP.NET features like security. Also, if you push views through SignalR you cannot get benefits from HTTP caching.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top