jBlogMvc : part 2 Editing, Deleting, Paging Posts and Rss feeds

NOTE: In this series I build a blogengine using ASP.NET MVC and jQuery from scratch in order to learn more about these new technologies. If you haven’t read the first post in this series, I would encourage you do to that first, or check out the jBlogMvc category. You can also always subscribe to the feeds.

What about new features this part will cover :

  1. Configuration is saved in the database.
  2. Managing Posts (Editing, Deleting).
  3. Posts are now paged.
  4. Some jquery magic is used.

So, lets have a tour in the project one more time. [more]

Database

Database has now a new table to read and write the blog settings.

The project design has changed I applied the Repository Pattern (as recommended in some feedback) , so know I have an extra layer I don’t plan on supporting other data stores but its a good practice (anyway this series is to learn).

Helpers

Pagination is added it has been discussed many times I will not repeat the code I got over here, for more about paging in ASP.NET MVC check the following excellent posts

Models

IBlogRepository and its implementation were added to this folder, the IBlogRepository is as listed here

public interface IBlogRepository
{
    #region Posts
    Post GetPostBySlug(string slug);
    Post GetPostByPemalink(Guid premalink);
    PagedList<Post> GetPostList(int pageIndex, int pageSize);

    void InsertPost(Post p);
    void UpdatePost(Post p);
    void DeletePost(Post p);
    #endregion

    #region Settings
    void SaveSetting(Setting s);
    Setting GetSetting(string settingKey);
    #endregion
}

 

Controllers

Still having the main two controllers (Home and Admin)  but many changes have came through, due to changing the structure and using repository.

Home Controller now sends a PagedList rather an ordinary List to the View, and I added a feed action which returns rss feeds of the blog as shown below

public ActionResult Feed()
{
    XDocument document = new XDocument(
        new XDeclaration("1.0", "utf-8", null),
            new XElement("rss",
                    new XElement("channel",
                        new XElement("title", Config.Instance.BlogName),
                        new XElement("link", "http://www.northwindtraders.com"),
                        new XElement("description", Config.Instance.BlogDescription),

                        from post in _repository.GetPostList(0, Config.Instance.BlogSyndicationFeeds)
                        orderby post.CDate descending
                        select new XElement("item",
                            new XElement("title", post.Title),
                            new XElement("description", post.Body),
                            new XElement("link", Request.Url.GetLeftPart(UriPartial.Authority) + post.RelativeLink)
                            )
                       ), new XAttribute("version", "2.0")));
    StringWriter sb = new StringWriter();
    document.Save(sb);

    return Content(sb.ToString(), "text/xml", Encoding.UTF8);
}

Admin Controller has a lot of additions as shown in the code listing.

[AcceptVerbs("GET")]
public ActionResult EditPost(Guid? id)
{
    if (!id.HasValue) return RedirectToAction("ManagePosts");
    Post p = _repository.GetPostByPemalink(id.Value);
    if (p == null) return RedirectToAction("ManagePosts");
    return View(p);
}

[AcceptVerbs("POST")]
public ActionResult UpdatePost(Guid id)
{
    Post p = _repository.GetPostByPemalink(id);
    if (!ViewData.ModelState.IsValid)
        return View("ManagePosts", p);

    try
    {
        UpdateModel(p, new string[] { "Title", "Body", "Slug", "CDate" });
        _repository.UpdatePost(p);
        return RedirectToRoute("Posts", new { slug = p.Slug });
    }
    catch
    {
        Helpers.UpdateModelStateWithViolations(p, ViewData.ModelState, System.Data.Linq.ChangeAction.Update);
        return View("ManagePosts", p);
    }
}

[AcceptVerbs("GET")]
public ActionResult DeletePost(Guid? id)
{
    if (!id.HasValue) return RedirectToAction("ManagePosts");
    Post p = _repository.GetPostByPemalink(id.Value);
    if (p == null) return RedirectToAction("ManagePosts");
    return View(p);
}

[AcceptVerbs("POST")]
public ActionResult RemovePost(Guid id)
{
    Post p = _repository.GetPostByPemalink(id);
    if (!ViewData.ModelState.IsValid)
        return View("ManagePosts", p);

    try
    {
        _repository.DeletePost(p);
        return RedirectToAction("ManagePosts");
    }
    catch
    {
        Helpers.UpdateModelStateWithViolations(p, ViewData.ModelState, System.Data.Linq.ChangeAction.Insert);
        return View("ManagePosts", p);
    }
}

public ActionResult ManagePosts(int? page)
{
    var posts = _repository.GetPostList(page ?? 0, 25);
    return View(posts);
}

public ActionResult GeneralSettings()
{
    return View();
}
public ActionResult ReadingSettings()
{
    return View();
}

Views

A lot of views were added in this part 2 other nested master pages have been added Admin_Manage and Admin_Settings for managing blog content and settings respectively some content views were added too.

  1. ManagePosts : Grid for all posts.
  2. EditPost : editing a post.
  3. DeletePost : confirm deleting a post.
  4. GeneralSettings : Blog Name, Blog description.
  5. ReadingSettings : Posts per page, syndication count.

I will not copy and paste code here, please take a look at the attached project.

jQuery

This part didn’t miss some of the jQuery magic as well, I found another interesting plugin called jEditable which allows ajax inline editing, its pretty cool and small, all you need to start using it, is an Action that accepts POST verbs and returns some value.

I used it here with the (Settings) panel to read and write blog settings, the following code snippet is from the GeneralSettings.aspx view page defined in the document ready event.

 

$("#blogname").editable('<%=Url.Action("UpdateSettings","Admin") %>', {
               submit: 'ok',
               cancel: 'cancel',
               cssclass: 'editable',
               width: '99%',
               placeholder: 'emtpy',
               indicator: "<img src='../../Content/img/indicator.gif'/>"
           });

 

<p>
    <label for="blogname">Blog Name</label>
    <span class="edt" id="blogname"><%=Html.Encode(jBlogMvc.Config.Instance.BlogName)%></span>
</p>

Its clear that this code snippet assigns the textbox with id blogname to an action called UpdateSettings found in the Admin controller, shown in the next code snippet

 

[AcceptVerbs("POST")]
public ActionResult UpdateSettings(string id, string value)
{
    foreach (var item in this.GetType().GetProperties())
    {
        if (item.Name.ToLower().Equals(id, StringComparison.InvariantCultureIgnoreCase))
            item.SetValue(Config.Instance, value, null);
    }
    return Content(value);
}

inline editing

So, in the action I accept two parameters sent id and value, sent by default by the jEditable plugin which can be configured to change the variable names, the action is expecting that there is a blogsetting  in the Settings table having a key macthing the id parameter for example (blogname), which I also expect having a matching Property name in the Config class (built using the singleton pattern).

I am pretty sure that this is not the best practice for this case, thats why I am in need for constructive feedback.

Summary

And that’s all for this part, I have more and more features coming while writing this engine I have learned much till now, hope someone is learning with me too.

In this part, I used some features of the ASP.NET MVC to complete the administration area I started last, jQuery too was used to make inline editing (jEditable plugin) so what do you think? you are most welcomed to leave comments.

Download version one : jBlogMvc_version_2.zip

If you liked this blog post then please subscribe to this blog.


Posted

in

,

by

Tags:

Comments

7 responses to “jBlogMvc : part 2 Editing, Deleting, Paging Posts and Rss feeds”

  1. lee Avatar

    Man this really is going to be a cool app when its finished…!! As soon as MVC is released fully, I’m going to be all over this tutorial. thanks again for posting it up

  2. Amr Avatar

    @lee
    Thanks man made my day 🙂
    I do really hope this finishes with something useful.

  3. Mohamed Avatar
    Mohamed

    This is going to be the best way for me to learn ASP.NET MVC, I can’t thank you enough….please keep up this AMAZING work, you ROCK!

  4. Amr Avatar

    @Mohamed
    Thank you

  5. Joel Avatar

    Hi Amr, this is a very clean and well designed MVC project. We must think alike 🙂 Anyway, keep going, this series rocks!

  6. Jarrett Avatar

    Great post. This is very similar to http://blogsvc.net which we recently moved over to MVC. It also using jQuery and open standards such as AtomPub. Supports both Atom and RSS feeds as well as comment feeds. However, we are missing the editing/deleting of posts. However, all of this can be done using AtomPub through Windows Live Writer.

  7. gorytus Avatar
    gorytus

    Excellent series, by far my favourite practical resource for exploring Aspnet MVC; looking forward to part3!

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *