Tag Archives: MVC

Adding Styles to Built in Editor Templates in Razor

I thought I’d blog about this thing I keep forgetting the syntax for and I’m sick of Googling for it. It’s a bit of a niche thing in Razor. First, some background.

Previous to MVC 5, you could not add any styling to any of the built-in EditorTemplates. So, if you wanted to add a Bootstrap style to an input, you had to fall back on the simple Editor extension method:


@Html.EditorFor(m => m.Name, new { @class = "input-lg"}) // won't work
@Html.Editor ("Name", new { @class = "input-lg"}) // used to be OK - before MVC 5

The EditorTemplate would simply ignore the style. And if it happened to be the first time you bumped up against that foible, you probably blew half a day figuring out that it was not supported.

Someone whispered in Microsoft’s ear, because they changed this in MVC 5 (possibly the 5.1 release). The following syntax enables you to have your cake and eat it:


@Html.EditorFor(m => m.Name, new { HtmlAttributes = new { @class = "input-lg" }})

Note, you now have to use that new syntax with the simple Editor extension method as well.

WebAPI Method Returning 404

There is something I absolutely hate when programming. When you hit a bump in the road that brings everything to a halt; and it is something which should definitely not be getting in the way. I hesitate to call them bugs. It’s just those little annoyances where I have overlooked some little thing and it has cost me hours.

Welcome to my day today. I had an ASP.NET MVC application which, when I created it, did not have the WebAPI stuff in the solution (I deliberately unchecked the checkbox which would have included all that stuff). So, when I decided that I did, in fact, want to use the WebAPI, I manually added all the necessary nuget packages etc.

There was one thing I got wrong. And troubleshooting this took me around 1.5 hours. Apparently, you need to register the WebAPI routes before the standard MVC routes:

protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  GlobalConfiguration.Configure(WebApiConfig.Register); // this 1st
  RouteConfig.RegisterRoutes(RouteTable.Routes); // then this
  BundleConfig.RegisterBundles(BundleTable.Bundles);
}

I’m not saying it shouldn’t be that way. It’s just that, when you are trying to get that thing, which should have taken 5 minutes, working 90 minutes later, you get a little peeved. Especially when you hear the clock ticking and time slipping away. In effect, it’s not even having wheels on the ground until the annoying oversight is rectified.

Filing this one under stuff I do not want to forget. Ever.

Javascript Variables Set Dynamically Server-side

I have been knocking this post around in my head for a couple of days now. It all started when I read this great post about how to use the jQuery DatePicker widget with ASP.NET MVC. In that post, the Stuart Leeks “hard-wires” the date format to be the UK format for the date-picker and leaves it to the reader to dynamically set that format as an exercise.

I recall my times in Webforms where the task of rendering ClientIDs for Server controls in Javascript was quite challenging. A lot of people wrote horrible code in their mark-up like:

'<%= SecurityCheckCompleteCheckBox.ClientID %>'

Ugh, grotesque. (I can’t count the number of dodgy forum posts which put that syntax forward as a solution). Guys with more enterprise experience wrote elegant code like this.

In MVC, it is a lot easier to accomplish this, given the fact that HTML ids are not generated for you by the ASP.NET runtime. But, we still may come up against a situation whereby we want to use a variable in a javascript file which you want to dynamically set at runtime.

For example, take the date format for the DatePicker in the blog post referred to above. There, the javascipt file has some script like this:

    $('.date').each(function () {
        var minDate = getDateYymmdd($(this).data("val-rangedate-min"));
        var maxDate = getDateYymmdd($(this).data("val-rangedate-max"));
        $(this).datepicker({
            dateFormat: "dd/mm/yy",  // UK format hard-coded
            minDate: minDate,
            maxDate: maxDate
        });
    });

The problem to solve is that you want to use a dynamically generated javascript variable so that the code looks more like this:

    $('.date').each(function () {
        var minDate = getDateYymmdd($(this).data("val-rangedate-min"));
        var maxDate = getDateYymmdd($(this).data("val-rangedate-max"));
        $(this).datepicker({
            dateFormat: SvrSideVariables.DateFormat,  // format set server-side
            minDate: minDate,
            maxDate: maxDate
        });
    });

As you are aware, you can’t write any kind of C#/server-side code inside a javascript file. And although you can do it in a script tag in the markup, script tags containing javascript content are evil, unless dynamically generated. The separation of presentation from behaviour requires that there be no javascript in the markup, unless it is just a script element pointing to an external javascript file.

What follows is a very basic solution to this problem. There are many approaches one could take to attacking this problem.
Lets set the dateformat variable in the web.config file, so we can change it without having to recompile.

  <appSettings>
    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    <add key="DateFormat" value="dd/mm/yy"/>
  </appSettings>

Then, we’ll just use a simple custom HtmlHelper to render that variable in a script tag, which we will add to the head section of our document:

        public static MvcHtmlString CreateServerSideVariables(this HtmlHelper helper, string variable)
        {
            // Create tag builder
            var builder = new TagBuilder("script");

            // Add attributes
            builder.MergeAttribute("type", "text/javascript");

            // We want a namespace, because as the great Douglas Crockford said, the Global namespace is eeevil.
            builder.InnerHtml = "if(typeof SvrSideVariables == 'undefined') var SvrSideVariables = { }; SvrSideVariables.DateFormat = '" + variable + "';";

            // Render tag.
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
        }
    }

Such a script tag is fine, because it keeps the markup which you have to maintain clean (no mixing of behaviour and presentation) and it is done dynamically at run-time. Make sure you add that element before your custom script, so the variable “SvrSideVariables.DateFormat” will be available for use by your custom script which uses it to set the date format for your datepicker.

Finally, use the helper (in the Edit.cshtml file):

@section ServerSideVariables{
    @Html.CreateServerSideVariables(ConfigurationManager.AppSettings["DateFormat"])
}

And of course in the _Layout.cshtml:

@RenderSection("ServerSideVariables", false)

That’s one of several approaches.

Get the code, which just augments the code from the original article:

HtmlHelper for Javascript Script Elements (Tags)

I wrote an HtmlHelper for Javascript elements which, I believe, makes for a more maintainable codebase for adding script elements to a view:

        public enum JavascriptPathType
        {
            Relative = 0,
            FullWebPath = 1
        };

        public static MvcHtmlString Script(this HtmlHelper helper, string jsFileName, JavascriptPathType pathType)
        {
            // Instantiate a UrlHelper
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

            // Create tag builder
            var builder = new TagBuilder("script");

            switch (pathType)
            {
                case JavascriptPathType.Relative: builder.MergeAttribute("src", urlHelper.Content("~/Scripts/" + jsFileName));
                    break;
                case JavascriptPathType.FullWebPath: builder.MergeAttribute("src", urlHelper.Content(jsFileName));
                    break;
            }

            // Add attributes
            builder.MergeAttribute("type", "text/javascript");

            // Render tag. Note: script tags have to have an End tag and cannot be self-closing.
            return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
        }

The most common scenario is where your javscript file is located in the Scripts directory of your project, in which case, all you need to do is pass in the name of the javascript file:

@Html.Script("jquery-1.8.2.min.js", JavascriptPathType.Relative);

This saves you from typing the script tags and the text type=”text/javascript” everytime.
I also added the custom enum JavascriptPathType to account for scenarios where the src of the script tag is pointing to someplace other than within your own project. For example, if you were using the Google maps API, the usage would be:

@Html.Script("http://maps.google.com/maps/api/js?sensor=false", JavascriptPathType.FullWebPath);

I’m thinking next will be the same kind of helper for Css files.

Twisting the Triad – MVC

I have spent a lot of time researching the difference between the MVC and MVP design patterns, as I could not really articulate those differences in a conversation, even though I have used them both in practice. When asking around, I found that a lot of other developers also did not actually know the difference either. So I was in good company.

When you go down this road, you encounter the phrase “Twisting the Triad”. The MVP pattern was arrived at by “Twisting the Triad” (among other things). But the many people who talk about twisting the triad never actually stop to explain what that means exactly. And when I started asking colleagues what is meant by that phrase, I was not surprised to find that no-one (not 1) person could explain what twisting the triad means. Rotating the nodes in the diagram is not quite good enough as an explanation because it has no context. And how far are they rotated? ** Blank looks all round **. Some guys thought it had something to do with the arrows in the diagram. Whilst the difference in the directed arrows between the MVC and MVP diagrams does encompass a huge part of the distinction between the 2 patterns, it does not, in any way, explain what “Twisting the Triad” means.

After much cogitation on the issue, I believed I worked it out one day during my morning shower. But I wanted back-up before I was sure. This theory gave me fresh keywords for Googling and I finally stumbled upon this post by a very well-respected guy in the ASP.NET MVC community. See the last paragraph under the heading The Difference?.

So, without further ado, let me explain what the phrase “Twisting the Triad” means, when used to explain how the MVC pattern evolved into the MVP patten. It is all about which node of the diagram is the first point of contact for the user gesture (or user request). Let me explain with an interactive diagram. The diagram below shows the MVC pattern with the nodes following this colour legend:

  • Red: Model
  • Green: View
  • Yellow: Controller

The arrow represents the user gesture. As you can see, with MVC, the first point of contact for the user gesture is the Controller, which then orchestrates how the application handles that user input.
Now, click the button with the text Twist the Triad!

User Gesture

When you twist the triad by clicking the button, the View now becomes the first point of contact for the user gesture, which is observed by the Presenter i.e. it raises events to the Presenter which then handles those events.

  • Red: Model
  • Green: View
  • Yellow: Presenter

So to recap, this post was about Twisting the Triad. I realise there are other differences between the two patterns. But I’m hoping this post clearly articulates the meaning of “Twisting the Triad”, which so many great developers cannot seem to explain.