Microsoft’s ASP.NET MVC Lite, Building a TextReformatter With JsonResult

 

Introduction

 

People often ask me if I use MVC or WebForms for my Microsoft ASP.NET projects.  I always tell them MVC, but I don’t use it in the classic way that most others do.  That is to say, I emit no html from my views, and for that matter really don’t even use views (with the exception of one view which is essentially my entire app.   People often refer to this as a SPA or Single-Page-Application. What this basically means is that my entire view is built with JavaScript (in my case Sencha’s ExtJS) and the only interaction with the server is to simply bring down Json results.

In this post, I’m going to build a simple app following this principle. It’s purpose will be to take a big pile of text, chop it up into words, then output it in some c# friendly manner.  My motivation for doing this is I happen to need that functionality right now and instead of creating a little awk script to do it, I’m going to right a web site!

 

So, Here is what we will build.  A handy formatter! (and you can run it at:   http://reformatter.peterkellner.net/ )

 

image

image

 

 

Part I, The Visual Studio Project

 

Let’s first create the Visual Studio project.  My development these days is actually using the latest Windows 8 Consumer build with the beta of Visual Studio 2011 running on it.  The nice thing about this is because Microsoft added “Round Tripping” to VS2011, I can now use VS2011 to create the project and you, my happy readers, can download the project and open it in Visual Studio 2010.  This has been long in coming and Microsoft has finally done it for the newest version of Visual Studio.  Thank you Microsoft!

 

image

 

And with an Internet Application with Razor (though I really don’t need all that extra stuff, it does not hurt)

 

image

 

The structure created is as as shown below with a Controller and Views folder and all the proper routing setup.

 

image

 

Because I want to make a very simple MVC app that only emits Json, Let’s create our own empty controller called ReformatterController.  We do that by right clicking on the Controller folder and pressing “Add Controller”, then “Add Empty Controller”.

image

 

Now, let’s create a very very simple controller with just one method that returns a JSON Result.  I’m returning the data in a friendly format to  Sencha’s ExtJS (or SenchaTouch for that matter).  JQuery would be similar.  Here is our new controller class (I’m sure my little tokenizer, line maker could be improved, but I’m just doing this to show some real work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MvcLiteApp.Controllers
{
    public class ReformatterController : Controller
    {
       
        public JsonResult ConvertTextToFriendlyText(string inputText)
        {
            const int maxCharactersInLine = 30;
            bool success;
            string messageReturn;
            var outputDataList = new List<string>();

            try
            {
                var words = inputText.Split(' ').ToList();
                var newLine = new StringBuilder();
                foreach (var word in words)
                {
                    if (newLine.Length + word.Length < maxCharactersInLine && 
                        word.Length < maxCharactersInLine)
                    {
                        newLine.Append(" ");
                        newLine.Append(word);
                    }
                    else
                    {
                        outputDataList.Add(newLine.ToString().Trim());
                        newLine = new StringBuilder();
                        newLine.Append(word);
                    }
                }
                success = true;
                messageReturn = "";
            }
            catch (Exception e)
            {
                messageReturn = e.ToString();
                success = false;
            }


            return Json(new
            {
                Success = success,
                Data = outputDataList,
                message = messageReturn
            }, JsonRequestBehavior.AllowGet);
        }

    }
}

Now, let’s feed it a URL and see what happens.  Here is a sample URL:

http://localhost:3600/Reformatter/ConvertTextToFriendlyText?inputText=Romeo%20Montague%20and%20Juliet%20Capulet%20meet%20and%20fall%20in%20love%20in%20Shakespeare’s%20lyrical%20tale%20of%20%22star-cross’d%22%20lovers.

I actually pasted the sentence in to the the browser’s URL line and it added the nice encoded spaces for me.  The output is as follows:

{"Success":true,"Data":["Romeo Montague and Juliet","Capulet meet and fall in love","in Shakespeare\u0027s lyrical tale"],"message":""}

Notice that it created the nice lines formatted as a JavaScript array!

Next step, let’s make a real JavaScript program out of this.

 

Part 2, Our SPA (Single Page App) That Does Real Work

 

I’m only going to explain here the part of the Sencha Program that actually consumes the data but first, let’s add a little “properness” to our controller so it responds only to POST.  That is, we add an attribute to the top of the method and we change the behavior attribute on the bottom to say to not allow get.

        [HttpPost]
        public JsonResult ConvertTextToFriendlyText(string inputText)
        {
            .......
            return Json(new
            {
                Success = success,
                Data = outputDataList,
                message = messageReturn
            }, JsonRequestBehavior.DenyGet);
        }

And, the JavaScript in the SPA is very straight forward and is here:

var beforeTextAreaComponent = Ext.getCmp('BeforeFormatTextAreaId');
textBefore = beforeTextAreaComponent.getValue();

// how to not pollute global name space here?
var stringbuildervalue = Ext.getCmp('stringbuilderid').getValue();
var javascriptarrayvalue = Ext.getCmp('javascriptarrayid').getValue();
var noformattingvalue = Ext.getCmp('noformattingid').getValue();
var outputwidthvalue = Ext.getCmp('outputwidthid').getValue();

Ext.Ajax.request({
    url: 'ReFormatter/ConvertTextToFriendlyText',
    params: {
        inputText: textBefore,
        stringbuilder: stringbuildervalue,
        javascriptarray: javascriptarrayvalue,
        noformatting: noformattingvalue,
        outputwidth: outputwidthvalue
    },
    success: function(response){
        var localData = Ext.JSON.decode(response.responseText).Data;
        var numberRows = localData.length;
        var newData = '';
        for (var i=0;i<numberRows;i++) {
            newData += localData[i] + '\n';
        }


        var afterTextAreaComponent = Ext.getCmp('AfterFormatTextAreaId');
        afterTextAreaComponent.setValue(newData);

    },
    failure: function(error) {
        alert('error');
    }

});

Now, in reality, I’ve added some useful stuff to the controller (and put the project here for your review, comments and suggestions).

Visual Studio Project TextReformatter.zip

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Follow

Get every new post delivered to your Inbox

Join other followers: