MVC Not the Magic Bullet

by Admin 1. July 2012 08:31

I have been working with ASP.MVC 3 fairly heavily for the past year and I am anxiously awaiting the production release of VS 11 and MVC 4.0.  I think ASP.MVC  is a fantastic platform and solves many of the issues that exist with ASP.Net webforms.  The issue that I have notice though is many people in the development community are touting it as a “Magic Bullet” of sorts.  I have heard “Development times will shrink when we move to MVC” or “This would be so much easier in MVC” or “You won’t have to worry about page bloat in MVC.”  These comments are really only half truths.  

Will development time speed up under MVC?  In the long run with competent architects, developers and designers timelines should shrink a small amount (I need more data to give exact numbers) in MVC. Developers can spend their time writing business logic without having worry about the impact to the UI (with some considerations).  Designers can focus on making the UI look good without worrying about to much ASP gobbledygook (with some considerations). In addition SEO competent designers will have a much easier time adding SEO compliance to the site (if that is your goal).

Will development get easier in MVC? Yes and no.  I would like to discuss this particular topic in three parts. First, there are many seasoned ASP.NET Web Form developers out there that are well versed in the page life cycle, web controls and the ins and outs of ASP.NET in general, and can deliver excellent web sites working in that framework.  MVC (razor in particular) will be a complete paradigm shift for them.  I have heard several developers compare it to classic ASP and they are a bit annoyed they are being pushed back in that direction.  This could not be further from the truth, but a cursory glance at MVC (especially non-razor) it is easy to see how you could jump to that conclusion.  The removal of view-state and control-state presents a new set of challenges when working with pages.  The heavy dependency on JavaScript and JQuery on validations, AJAX and UI will be a bit of a learning curve for web developers that have only had to deal with that on a cursory level.  It is now, in my opinion, impossible to keep developers shielded from JavaScript and to a point even CSS.  Most developers are already comfortable in these areas but I know of several that only use the two when absolutely necessary.

Secondly, MVC (and HTML 5) blurs the lines between behavior, formatting and content which traditionally follows this model:

Web Block

The new model looks something like this:

Web Venn

Leading to questions of what should I use and when?  There really is no hard and fast answer to that question.  I usually use the following as a guide line in order of importance?  

Target Browser Compatible > Robustness of Functionality > Ease of Implementation > Maintainability

This wasn’t as much of a concern in ASP.NET Webforms as many of the web controls used handled all three aspects in their server side properties.  Which brings me to my third topic; the lack of standardized custom controls with ASP.NET MVC.  With ASP.NET MVC there is no such beast as a “Web Control”, there are only HTML helpers, JavaScript and JQuery libraries.  The big component players (Telerik, Infragistics and ComponentOne) are providing some JQuery libraries and MVC libraries but not much that competes with the free items already out there also JQuery changes so often that using version based component specific JavaScript and CSS really limits your ability to keep up to date.  I found out the hard way trying to go with the old model of “buy rather than build” can severely limit your options.  Recently I have been going the way of “find and tweak rather than build from scratch.”  GitHub and CodePlex are becoming the new source of third party components.  These controls however are purely an implementation of HTML, JavaScript/JQuery and CSS.  They are not server code specific.  So throw out the idea of setting some properties in the designer and it just working.

Lastly, can developers be completely oblivious to page bloat?  Absolutely not, page bloat has just shifted from viewstate to JavaScript includes and CSS.  Finding all of the controls to replace existing libraries comes with the price of including more and more .JS files.  So if you think you are trading you 500k viewstate for 0k MVC, guess again.  If you are not careful it could be 500k viewstate for 1 meg of added script.  Luckily MVC 4 is working on combatting that issue with bundling, but that isn’t a magic bullet either.

The long and short; if you were slashing timelines and removing servers from you web farms because you thought all of your problems were solved.  You are gonna find yourself up “bit” creek without a paddle.

 

Tags: , , ,

ASP.NET | CodePlex | GitHub | HTML5 | MVC3

JQuery Tooltips with MVC3 and CSS 3.0 (Part 2)

by Admin 25. March 2012 02:56

So in my previous post I explained all of the steps required to create a simple but effective CSS 3 JQuery tooltip implementation.  This was a good start, I had all I needed to fulfill my requirement of a consistent tooltip in my application.  But I needed it to be a little easier to use throughout the application.  A custom Html Helper Extension to the rescue. Creating an HTML Helper is a pretty straight forward task this one, however, needed a bit of special sauce to make it work the way I wanted.

First I wanted to make sure I could bind it to my model, in case in the future I wanted to default it to the [Display] property on the model.  Second I wanted to be able to use the @<text></text> syntax for the contents of the tooltip.  It made sense to work backwards I wanted the control to work like this: 

@Html.InfoTooltipFor(model => model.ToolTipTitle,
	@<text>
	<h4>@Model.ToolTipTitle</h4>
	<ul>
   		<li>
			<b>Scott Guthrie</b> – 
			<a href="http://weblogs.asp.net/scottgu/">
				ScottGu's Blog
			</a> One of the best resources for all things Microsoft Web
                </li>
		<li>
			<b>Scott Hanselman</b> – 
				<a href="http://www.hanselman.com/blog/">
					Scott Hanselman's Computer Zen
				</a> Another great resource very current and very informative.
		</li>
		<li>
			<b>ASP.NET</b> – 
				<a href="http://www.asp.net/mvc">
					ASP.NET MVC
				</a> The mother of all things ASP.NET MVC
		</li>
     </ul>
</text>)

 

Seemed simple enough so at first I create the Helper as follows:

 

public static MvcHtmlString InfoTooltipFor<TModel, TValue>(
    this HtmlHelper<TModel> html, 
    Expression<Func<TModel, TValue>> expression, 
    string tooltip)
{
...
}

 

Nope that won't work... 

 

And once I thought about it makes sense that a string won't work.  It isn't anything remotely like a string it contains functions, delegates and properties. I know this type of implementation exists I have seen it in other controls.  So how is it done?  After an exhaustive google search I found this article by Phil Haack.  It was close to what I needed, so, after some trial and error I came up with this:

public static MvcHtmlString InfoTooltipFor<TModel, TValue>(this HtmlHelper<TModel> html, 
		Expression<Func<TModel, TValue>> expression, 
		Func<object, HelperResult> tooltip)
{
	//Get the Model metadata
	ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
	string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
	string tooltipId = metadata.PropertyName ? ? htmlFieldName.Split('.').Last();

	if (String.IsNullOrEmpty(tooltipId))
	{
		return MvcHtmlString.Empty;
	}
	//creates the span tag for the image
	TagBuilder spanTag = new TagBuilder("span");
	spanTag.MergeAttribute("class", "tooltipItem");
	spanTag.MergeAttribute("id", tooltipId);
	spanTag.MergeAttribute("data-tooltip", "tt" + tooltipId);

	TagBuilder imgTag = new TagBuilder("img");
	imgTag.MergeAttributes(new RouteValueDictionary(
		new
		{
			@class = "infoimage",
			src = UrlHelper.GenerateContentUrl("~/Content/info.png", html.ViewContext.HttpContext),
			alt = "info"
		}
		));
	spanTag.InnerHtml = imgTag.ToString(TagRenderMode.Normal);

	//creates the tooltip contents
	TagBuilder tooltipTag = new TagBuilder("div");
	tooltipTag.MergeAttribute("class", "hidden");
	tooltipTag.MergeAttribute("id", "tt" + tooltipId);
	tooltipTag.MergeAttribute("name", "tt" + tooltipId);
	tooltipTag.MergeAttribute("data-tooltip", "tt" + tooltipId);
	tooltipTag.InnerHtml = tooltip(null).ToString();

	return MvcHtmlString.Create(spanTag.ToString(TagRenderMode.Normal) + tooltipTag.ToString(TagRenderMode.Normal));
}

The key is Func<object, HelperResult> this allows templated items to be passed into helper method.  This was exactly what I needed and poof like magic it worked.  MVC is awesome, creating a control like that in standard ASP.NET would have been a major pain. 

The entire solution is in the attached zip...

EasyTooltips.zip (2.46 mb)

Tags: , , , ,

AJAX | css | jquery | MVC3

MVC Makes AJAX easier

by Admin 12. February 2012 19:07

MVC is a pretty new paridigm to me, I just started using it about 5 months ago, but one of the first things I noticed is how much easier it has made AJAX.  This is coming from someone who has had a very long career in ASP.NET.  There were a few different ways to provide Ajax functionality in ASP.NET the evil update panel being the easiest to implement.  My preference and, IMO, the more correct approach was to use the AJAX framework in conjunction with AJAX Aware WCF/Web Services.  The low framework overhead (no Eventing Model) in conjuction with the relatively small request/response package made these fairly easy to implement and perform very well.  The problem with these services is they were still tied up in all sorts of framework gook.

With MVC, all of that framework gook is gone, it is a much simpler PHP style implementation of AJAX.  There are several ways to utilize AJAX in the MVC world, there are the AJAX MVC Helper Class which is very easy to work with, but I perfer a pure JQuery ajax approach.

Enough talk here is an example of a simple implementation of ajax using 4 commonly used methods:

First the Controller (in this case I am using the Products table of the Northwind Database (kickin' it old school)):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
 
namespace JqueryAjax.Controllers
{
    public class ProductsController : Controller
    {
        //
        // GET: /Products/
 
        public ActionResult Index()
        {
 
            List<Product> prodList = null;
            using (NorthwindEntities ctx = new NorthwindEntities())
            {
                prodList = ctx.Products.OrderBy(p => p.ProductName).ToList();
 
            }
            return View(prodList);
        }
 
        public ActionResult _productInfoJSON(int? id)
        {
            Product prod = null;
            using (NorthwindEntities ctx = new NorthwindEntities())
            {
                prod = ctx.Products.Single(p => p.ProductID == id);
 
            }
            return Json(prod, JsonRequestBehavior.AllowGet);
        }
 
        public ActionResult _productInfo(int? id)
        {
            Product prod = null;
            using (NorthwindEntities ctx = new NorthwindEntities())
            {
                prod = ctx.Products.Single(p => p.ProductID == id);
 
            }
            return PartialView(prod);
        }
 
        [HttpPost]
        public ActionResult _productInfoJSONParams()
        {
            Product prod = null;
            int prodId = int.Parse(this.ValueProvider.GetValue("id").AttemptedValue);
            using (NorthwindEntities ctx = new NorthwindEntities())
            {
                prod = ctx.Products.Single(p => p.ProductID == prodId);
 
            }
            return Json(new { prod.ProductName, prod.UnitPrice });
        }
 
    }
}

I use the "_" syntax to denote partial actions and views.  So looking at the above code you will notice there is only one full action "Index", so lets look at its view:

@model IEnumerable<JqueryAjax.Product>
 
@{
    ViewBag.Title = "Products List";
}
 
@section script{
    <script src="@Url.Content("~/Scripts/Info.js")" type="text/javascript"></script>
}
<h2>Index</h2>
<table>
    <tr>
        <th>
 
        </th>
        <th>
            ProductName
        </th>
    </tr>
 
@foreach (var item in Model) {
    <tr>
        <td>
            <a class="prodInfo" href="#" data-product-id="@item.ProductID">
                <img src="../../Content/Images/info.jpg" width="20" height="20" alt="info" border="0" />
            </a>
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ProductName)
            <div id="product-@item.ProductID" style="display:none;">
            </div>
        </td>
    </tr>
}
 
</table>
So in this view I am simply building a Table of product names with an info image, easy peasy.  The Ajax parts of the html are housed in the:
 
<div id="product-@item.ProductID" style="display:none;">
And the:
<a class="prodInfo" href="#" data-product-id="@item.ProductID">

The former is the place holder for our dynamic content and the latter is the link to our dynamic content.  Now that we have all of the page scaffolding in place we need to hook up the pieces.  There are several ways we can retrive the content.  We could retrieve a standard JSON object from a controller _productInfoJSON and _productInfoJSONParams or you can return a partial view.  This is where the power of MVC really hits home.  You can craft a fully functional page and return it to your AJAX container.  That is pretty sweet...  But first lets look at the JSON example:

I created 2 a JSON Get (useful for RESTful services) and a JSON Post (prefered for internal web site calls):

Here is the Java script for calling the JSON get in conjuntion with the previously crafted view and controller:

/// <reference path="jquery-1.7.1.min.js" />
$(document).ready(function () {
    $(".prodInfo").click(function (e) {
        //stop the href="#" from firing
        e.preventDefault();
 
        var prodId = $(this).data("productId");
        jsonGet(prodId);
 
    });
});

function jsonGet(prodId) {
    $.ajax({
        url: "/Products/_productInfoJSON/" + prodId,
        success: function (data) {
            $("#product-" + prodId).toggle();
            $("#product-" + prodId).html("<span> price:"+ data.UnitPrice +"</span>");
        }
    });
}
and the JSON parameterized post:

jsonPost(prodId);

function jsonPost(prodId) {
    $.ajax({
        url: "/Products/_productInfoJSONParams",
        type: "POST",
        data: { id: prodId },
        success: function (data) {
            $("#product-" + prodId).toggle();
            $("#product-" + prodId).html("<span> price:" + data.UnitPrice + "</span>");
        }
    });
}

This will get you a simple return value that you can format in JQuery.

Pretty simple right?  Well its about to get easier.  Now lets say we want to return a significant amount of data to the client and we don't want to do that messy JavaScript HTML formatting.  Partial Views to the rescue.  Create the following partial view from the _productInfo action:

@model JqueryAjax.Product
 
<fieldset>
    <legend>Product Info</legend>
 
    <div class="display-label"></div>
    <div class="display-field">
        QuantityPerUnit: @Html.DisplayFor(model => model.QuantityPerUnit)
    </div>
 
    <div class="display-field">
        UnitPrice: @Html.DisplayFor(model => model.UnitPrice)
    </div>
 
    <div class="display-field">
        UnitsInStock: @Html.DisplayFor(model => model.UnitsInStock)
    </div>
 
    <div class="display-field">
        UnitsOnOrder: @Html.DisplayFor(model => model.UnitsOnOrder)
    </div>
 
    <div class="display-field">
        ReorderLevel: @Html.DisplayFor(model => model.ReorderLevel)
    </div>
 
    <div class="display-field">
        Discontinued: @Html.DisplayFor(model => model.Discontinued)
    </div>
</fieldset>

Now change the JS click event to fire:

partialJqueryGet(prodId);

with the function definition of:

function partialJqueryGet(prodId) {
    $.get("/Products/_productInfo/" + prodId,
    function (data) {
        $("#product-" + prodId).toggle();
        $("#product-" + prodId).html(data);
    });
}

BA BAM done.  Now you are returning a partial view from an ajax call.  You can also use a pure jquery ajax implementation as opposed to the Get helper class:

function partialAjaxGet(prodId) 
{
    $.ajax({
        url: "/Products/_productInfo/" + prodId,
        success: function (data) {
            $("#product-" + prodId).toggle();
            $("#product-" + prodId).html(data);
        }
    });
 
}

 

All of the code and the northwind database can be found here:

JqueryAjax.zip (2.67 mb)

http://www.microsoft.com/download/en/details.aspx?id=23654

 

Tags: , , , , , ,

AJAX | ASP.NET | jquery | JSON | MVC3 | Razor

Noobie frustrated by nuGet

by Admin 22. January 2012 20:44

So I am fairly new to MVC 3 but I did want to use the latest version of jQuery.  To my disappointment the default MVC 3 project comes with jQuery version 1.5.1.  Now, for my first MVC3 Razor project I just updated all of the script files manually.  That was quite annoying, then I found my savior (so to speak) nuGet.  NuGet should allow me to update the jQuery files via a simple simple Package Manager Console command "update-package jquery".  It can't be this simple...

Well guess what it isn't, again I was only given half the story.  So blissfully ignorant I proceeded to run the command:

PM> update-package jquery
Successfully installed 'jQuery 1.7.1'.
Update-Package : Conflict occurred. 'jQuery 1.5.1' referenced but requested 'jQuery 1.7.1'. 'jQuery.vsdoc 1.5.1, jQuery.Validation 1.8.0, jQu
ery.UI.Combined 1.8.11' depend on 'jQuery 1.5.1'.
At line:1 char:15
+ update-package <<<< jquery
+ CategoryInfo : NotSpecified: (:) [Update-Package], InvalidOperationException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.UpdatePackageCommand

 

Huh, success but failure.  So in my research I found the following command:

PM> get-package

Id Version Description
EntityFramework 4.1.10331.0 DbContext API and Code First workflow for ADO.NET Entity Framework.
jQuery 1.5.1 jQuery is a new kind of JavaScript Library....
jQuery 1.7.1 jQuery is a new kind of JavaScript Library....
jQuery.UI.Combined 1.8.11 jQuery UI is an open source library of interface components — interactions, full-featu...
jQuery.Validation 1.8.0 This jQuery plugin makes simple clientside form validation trivial, while offering lot...
jQuery.vsdoc 1.5.1 Includes vsdoc files for jQuery 1.5.1 that provide IntelliSense in Visual Studio 2010....
Modernizr 1.7 Modernizr adds classes to the <html> element which allow you to target specific browse...

Ok lets think about this, incompatable errors, a bunch of different pacakages of course .  After some trial and error I came up with the following order in which to run the updates:

update-package jQuery.UI.Combined
update-package jQuery.Validation
update-package Moderniz
update-package jQuery.vsdoc
update-package jQuery

This order allows jquery to update via nuGet correctly.  I hope this helps other frustrated nuGet noobs.

Tags: , , ,

jquery | MVC3 | nuGet | Razor

Calendar

<<  June 2017  >>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

View posts in large calendar

Page List

RecentComments

None