Create a blog with JQuery Mobile and ASP.NET MVC 3 with C#

Post to Twitter

I wrote an article not to long ago that showed you how to build a Mobile Blog with PHP and the new JQuery Mobile framework (the Alpha 3 version). Today I’ve taken that article and converted the code to ASP.NET MVC 3 (C#).

Note: Please keep in mind this is my first pass at converting this from PHP to ASP.NET MVC 3 and its very possible things are not where they “should” be. I know I left some things out on purpose for the sake of simplicity like client side and server side validations. These can be added into the project and in fact you’ll find the tutorials here a great help with that. This is the bare minimal code to get the Mobile Blog up and running, nothing more.

I created a new project and then used the Library Package Manager to add the (Code First) Entity Framework (CTP5) to the project.

I then added a class called Post to the Models folder with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MobileBlog.Models
{
	public class Post
	{
		public int ID { get; set; }
		public string Title { get; set; }
		[DataType(DataType.MultilineText)]
		public string Content { get; set; }
		public DateTime PublishDate { get; set; }
	}

	public class PostDBContext : DbContext
	{
		public DbSet<Post> Posts { get; set; }
	}
}

This re-creates the same scheme I had for the PHP/MySQL Mobile Blog project. I also then created another class to the Models folder called PostInitializer to re-create the database and seed it with data as required. Here is the code for that class:

using System;
using System.Collections.Generic;
using System.Data.Entity.Database;

namespace MobileBlog.Models
{
	public class PostInitializer : DropCreateDatabaseIfModelChanges<PostDBContext>
    {
        protected override void Seed(PostDBContext context)
        {
            var posts= new List<Post> { 
 
                 new Post { Title = "My new blog", 
							 Content = "This is my first blog post...",
                             PublishDate= DateTime.Now}, 
 
                 new Post { Title = "Second post", 
							 Content = "This is my second blog post. Hi!",
                             PublishDate= DateTime.Now}  
             };
            posts.ForEach(d => context.Posts.Add(d));
        }
    }
}

That requires a change to the web.config (for the connection string) and the Global.asax.cs file.

To the Application_Start() in the Global.asax.cs file I added the following line:

DbDatabase.SetInitializer<PostDBContext>(new PostInitializer());

…as well as this:

using System.Data.Entity.Database;
using MobileBlog.Models;

The connection string for the web.config file is as follows:

  <connectionStrings>
    <add name="PostDBContext"
         connectionString="Server=.\SQLEXPRESS; 
         Database=Posts;Trusted_Connection=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

Going into the Views/Shared folder no I modified the _Layout.cshtml file to be a good template for the project and to be in HTML5 format as well as to use the JQuery CDN to import the JQuery and JQuery Mobile frameworks.

<!DOCTYPE html>
<html lang="en-us" >
<head runat="server">	
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>MobileBlog</title>
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />
	<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js"></script>
</head>
<body>
    <div data-role="page">
        <div data-role="header">
            <h1>@ViewBag.HeaderString</h1>
        </div>
        <div data-role="content">
            @RenderBody()
        </div>
        <div data-role="footer"><h1>- MobileBlog -</h1></div>
    </div>
</body>
</html>

I then added a HomeController with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobileBlog.Models;

namespace MobileBlog.Controllers
{
    public class HomeController : Controller
    {
		PostDBContext db = new PostDBContext();

        public ActionResult Index()
        {
			ViewBag.HeaderString = "Welcome!";
            return View();
        }
				
		public ActionResult Create()
		{
			ViewBag.HeaderString = "Create New Post";
			return View();
		}

		public ActionResult Read()
		{
			ViewBag.HeaderString = "Read Blog";

            var posts = from p in db.Posts
                         select p;

            return View(posts.ToList());
		}

		public ActionResult About()
		{
			ViewBag.HeaderString = "About MobileBlog";
			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public string SavePost(string title, string content)
		{
			Post post = new Post();
			post.Title = title;
			post.Content = content;
			post.PublishDate = DateTime.Now;

			if (ModelState.IsValid)
			{
				db.Posts.Add(post);
				db.SaveChanges();
				return "SUCCESS";
			}
			else
			{
				return "FAILED";
			}			
		}
    }
}

From that controller I generated views for the following pages: About, Create, Index, and Read.

File: About.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div data-role="fieldcontain">
    <p><a href="http://giantflyingsaucer.com/blog/">MobileBlog</a></p>
    <p>Created by: <a href="http://twitter.com/chadlung">Chad Lung</a></p>
    <p>Powered by: <a href="http://jquerymobile.com">JQuery Mobile</a></p>
</div>

File: Index.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<ul data-role="listview">
	<li>
		@Html.ActionLink("Create New Post", "Create")
	</li>
	<li>
		@Html.ActionLink("Read Blog", "Read")
	</li>
	<li>
		@Html.ActionLink("About MobileBlog", "About")
	</li>
</ul>

File: Create.cshtml

@model MobileBlog.Models.Post

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script type="text/javascript">
    function resetTextFields()
    {
        $("#Title").val("");
        $("#Content").val("");
    }
 
    function onSuccess(data, status)
    {
        resetTextFields();
        // Notify the user the new post was saved
        $("#notification").fadeIn(2000);
        data = $.trim(data);
        if(data == "SUCCESS")
        {
            $("#notification").css("background-color", "#ffff00");
            $("#notification").text("The post was saved");
        }
        else
        {
            $("#notification").css("background-color", "#ff0000");
            $("#notification").text(data);
        }
        $("#notification").fadeOut(5000);
    }

    $(document).ready(function() {

        $("form[action$='SavePost']").submit(function () {
			$.ajax({
                url: $(this).attr("action"),
                type: "post",
                data: $(this).serialize(),
                success: onSuccess
            });
            return false;
        });
 
        $("#cancel").click(function(){
            resetTextFields();
        });
    });
 
</script>

@using (Html.BeginForm("SavePost", "Home", FormMethod.Post))
{
	<div data-role="content">
		<form id="newPostForm">
			<div data-role="fieldcontain">
				@Html.LabelFor(model => model.Title, "Post Title")
				@Html.EditorFor(model => model.Title)

				@Html.LabelFor(model => model.Content, "Post Content")
				@Html.TextAreaFor(model => model.Content)
 
				<fieldset class="ui-grid-a">
					<div class="ui-block-a">@Html.ActionLink("Cancel", "Index", null, new { @data_role = "button" })</div>
					<div class="ui-block-b"><button data-theme="b" id="submit" type="submit">Submit</button></div>
				</fieldset>
				<h3 id="notification"></h3>
			</div>
		</form>
	</div>
}

File: Read.cshtml

@model IEnumerable<MobileBlog.Models.Post>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script type="text/javascript">
    $(document).ready(function() { 
        $("#refresh").click(function(){
            location.reload();
        });
    });
 
</script>

<button data-theme="b" data-role="button" data-iconpos="left" id="refresh" type="button" data-icon="refresh">Refresh</button>
<ul data-role="listview" data-theme="d" data-inset="true">

	@foreach (var post in Model) {	 
		<li><h2>@post.Title</h2>@post.Content<p class="ui-li-aside"><strong>@post.PublishDate</strong></p></li>
	}
</ul>

So the code is familiar to the PHP code in most regards. Running the project in the Android emulator I get the same results as the PHP project before. BTW, I used the following address (because the Android emulator currently can’t use localhost for this type of thing): http://10.0.2.2

Post to Twitter

This entry was posted in ASP.NET, C#, HTML5, JavaScript, Mobile. Bookmark the permalink.

13 Responses to Create a blog with JQuery Mobile and ASP.NET MVC 3 with C#

  1. Pingback: Create a blog with JQuery Mobile and ASP.NET MVC 3 with C#

  2. Pingback: Tweets that mention Create a blog with JQuery Mobile and ASP.NET MVC 3 with C# -- Topsy.com

  3. sv says:

    Where can i download the source code?

  4. Chad Lung says:

    @sv,

    The source is in the article. Things like web.config, etc. are all the default (unchanged) from the new project wizard.

    Chad

  5. Doug S says:

    I believe the connection string’s database name should probably be called “posts” or something like that instead of movies ;) .

  6. Chad Lung says:

    @Doug,

    Whoops! Thanks, I’ve updated the article.

    Chad

  7. Doug S says:

    Should this also work on the WP7? I get the page showing up with the correct formatting on my pc browser, when I try to use it with the WP7 emulator, its all just plain text. Any ideas?

  8. Chad Lung says:

    #Doug,

    Windows Phone 7 isn’t a supported platform at the moment, see this for more details:
    http://jquerymobile.com/gbs/

    Chad

  9. John Barrett says:

    in the Global.asax file i get a compile error:

    ‘System.Data.Entity.Database’ is a type not a namespace’

    have things changed lately?
    i installed the EF code first stuff – which is now part of EntityFramework. perhaps that’s where it’s going wrong…

  10. John Barrett says:

    answered myself – they changed the object name so it should read:
    System.Data.Entity.Database.SetInitializer(new PostInitializer());

    30 min wasted :-)

  11. Eugene says:

    Great article about mvc 3. thank you very helpful

  12. prepaid mobile says:

    Informative info , I am involving in marketing field but before some time i am also involve in mobile app development .thanks for this info

  13. Pingback: No more native (I think) « Fredde's Android Dev

Comments are closed.