Skip to content

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

Updated: at 02:12 PM

 

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 {

    <span class="kwrd">public</span> JsonResult ConvertTextToFriendlyText(<span class="kwrd">string</span> inputText)
    {
        <span class="kwrd">const</span> <span class="kwrd">int</span> maxCharactersInLine = 30;
        <span class="kwrd">bool</span> success;
        <span class="kwrd">string</span> messageReturn;
        var outputDataList = <span class="kwrd">new</span> List&lt;<span class="kwrd">string</span>&gt;();

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


        <span class="kwrd">return</span> Json(<span class="kwrd">new</span>
        {
            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’; }

    <span class="kwrd">var</span> afterTextAreaComponent = Ext.getCmp(<span class="str">'AfterFormatTextAreaId'</span>);
    afterTextAreaComponent.setValue(newData);

},
failure: <span class="kwrd">function</span>(error) {
    alert(<span class="str">'error'</span>);
}

});

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

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects