ASP.Net MVC 2/C# 4… Dynamic Model and Should You Use It?

So there’s a new sheriff in town and its name is dynamic. Actually, its not really that new and that’s a horribly misused cliche. My lack of literary genius aside, I’ve been looking for a reason to use dynamic. Then it came to me: Models. Now the only reason why I started down that path was the use of Python where pretty much anything is dynamic. In using python, I got used to not embracing the rigidity of classes for models and adopted a more “Oh what the f–k” attitude. Back in the .net world though, I was using typed views. Then I readopted the “Oh what the f–k” attitude and applied it to .net mvc.

Here’s an example:

    public ActionResult ShowBasicInfo()
      IState currentState = ObjectFactory.Create();
      dynamic returnModel = new ExpandoObject();

      returnModel.UserName = currentState.CurrentUser.UserName;

      return View(AccountActions.ShowBasicInfo, returnModel);

As you can see, I created a dynamic class and just added a property to it. Now on the view side:

@model dynamic
          <label id="showBasicInfoEmail" name="showBasicInfoEmail">@Model.UserName</label>

So if that’s all you’re here for, well there you go. Now get out.

Ok so the real point to this post was actually the “should I?” Now with .Net, you really have to adopt a “should I?” attitude on anything that is new otherwise it might come back to bite you in the a–. (Update panels anyone?) Just using something because it looks easier is NOT a reason to do so.

The reason why I originally gravitated toward typed views was I didn’t like all the magic sting junk that came with the View dictionary, or whatever the hell it was called. (I’m too lazy to look it up) Typed views gave a sort of concrete nature much like an interface does to a class. You knew exactly WHAT the view could show based on the model. This is good I still think in an environment where you don’t trust people to code correctly or when a person needs an easy place to look up what the incoming model contains. After all, on the second point I mean, its a lot easier to look at a class to find EXACTLY what the model has than looking at a controller action code. Simple for reference.

With that being said, getting stuck in model hell can happen. After all for every action there is an equal and… wait… there is a model. Yeah you can reuse models to cut that down, but its not too hard to imagine it becoming a model infested nightmare. Sometimes you just have to take the good and the bad, but sometimes you’re able to trust people and just go with what is easier.

Why trust? With Python and it overall dynamic nature, it was easy to see that such a tool put in the wrong hands could be a disaster. Anyone who has worked with JavaScript will know this pain. Python is just a fancy way to annihilate your foot, so the concept of allowing dynamic models only made me shiver like a prostitute on Christmas. Sorry, that wasn’t appropriate. I meant a prostitute on a non religious holiday like Thanksgiving or the Chinese New Year. (Sorry non Christian readers)

On the other hand, when in a small group where you have less time and more to do, it could be used as a compromise as it doesn’t use the hated magic string dictionary thing approach, but still had a class like feel. And on top of that, if you wish to create models later, it would be extremely easy to swap the @model dynamic with whatever class type you need. So in that way, I can almost stop my non stop convulsing that is a natural reaction to doing something I deem bad.

Answer is: I don’t f–king know right now, but I’m going to fly with it and see how I like it.

Side note: One drawback of the dynamic route is the lack of intellisense. That could be a deal killer for some.

jQuery: Find a Form Action Using Jquery

This is pretty useful for people trying to pass in a generated action to a javascript file.  Eh?


Say you are using the jQuery post method to send things back to the server but all the code for that is in a seperate javascript file.  Well you can’t really do this:

      url: <%= someMethodForCreatingAUrl('controller', 'action') %>,
        email: user.userName,
        password: user.password
      success: function(result){
      error:function (xhr, ajaxOptions, thrownError){

if that is in the javascript file.

What you can do is this on the html file:

  <form id="formCreateUser" name="formCreateUser" method="post" action="${someMethodForCreatingAUrl('controller', 'action')}">

And in the javascript file:


  var formAction = jQuery(ELEMENT_LOGIN_FORM).attr('action');

And there you go. You have the action.

Spark View Engine, ASP.Net MVC, and You

So one of the things I was forced to use, semi kicking and screaming, at one point in my illustrious career was the Spark View Engine for ASP.Net MVC. Actually that’s not totally true. I only kicked for a bit then skipped the screaming once I noticed what it did: It took all the ugly <% %> junk out of the html… my beautiful html… and made things like for loops much nicer. Mind you, this is mererly the tip of the ice pick… eh berg I meant berg… there’s a lot more to it. It handles things like Master Pages and Partial Controls pretty darn well as well as caching javascript files on the go. Sounds good? Well it should and if it doesn’t, I don’t think we can be friends.

First off, I just wanted to quickly write something up on how to get it all going and because I’m such a nice guy I even have a project that is ready to go for common use. The catch is that I made it in 2010 so if you don’t have that yet, you could be screwed. Then again I could type out a lot of the steps too. You just don’t know.

First off you can either get the assemblies from my hosted project, or you can go here and get it. Either way, I don’t care. No really, I don’t. Not just sayin’. The care cup had run dry.

The two assemblies you need to reference in your project are:


Next add this line to the Application_Start method in the Global.asax.cs file:

  ViewEngines.Engines.Add(new SparkViewFactory());

After that, you’ll have to add a little somethin’ somethin’ to your web.config. I know, I know. This is all so very hard. Live strong like Lance.

      <section name="spark" type="Spark.Configuration.SparkSectionHandler, Spark"/>
      <compilation debug="true" defaultLanguage="CSharp">
          <add assembly="PhotoShare.UI" /> //Whatever the actual UI project is
      <pages automaticEncoding="false"> //If you want it to auto HTML encode post/get stuff
          <add namespace="System"/>
          <add namespace="System.Collections.Generic"/>
          <add namespace="System.Linq"/>
          <add namespace="System.Web.Mvc"/>

Ok so the web config is ready. Now what?

Well now you are going to create a master page. That’s right you are. Don’t fight me on this. I’m way cooler than you.

There is a little directory structure hard coding going on since by default you have to have things in certain places for Spark. Oh well. All Master Pages go in a directory named “Layouts” in the “Views” directory. So something like:


D— it. Forgot about that little tid bit too. Spark files have to be named .spark. Well actually I think there’s a way to call them whatever you want, but lets just go with defaults for now smarty pants.

And for the hard part, the html for the master page.

        <use content="Middle" />

HOLY HECK THAT’S HARD! Now there needs to be a controller. So just create one in the controllers folder. In my project it’s called this:


And then go ahead and create a view for index. Once you’ve done that, rename the extension from aspx to spark. Now for the html:

  <use master="Application"/>

    <content name="Middle">
        hi there

And that’s it really. As you can see, the placeholder on the master page (use content=”Middle”) is referred to on the child page.

To make testing this page easy, I would suggest changing the routing in the Global.asax.cs file to:

          new { controller = "SparkTest", action = "Index"}

And you should see something like:

  hi there aasdfasdfa

Proving that both the master page and the child page are printing stuff out.

You might be wondering why you should do all of this? If you aren’t, you are one hell of a lemming. And not the cool kind like those little guys that blow themselves up for the betterment of the lemming collective.  You’re that stupid one the just sits there with its hand out shaking its head.

A quick example:

       <div> hihihihih </div>

Compared to:

  <div if="something.IsTrue"> hihihihih </div>

Small example, but I think its pretty obvious why the second is so much better. And this is just scratching the surface on what spark does really.  I’d suggest looking here for more. I’d also suggest a new hair cut because… just wow. gets a shiny new tool!

A while back, we put up an offer to write for our blog.  Only one has risen to the top as someone having both the technical know-how and the razor sharp wit required to write on a site such as this. Readers… Amy.

Amy… Readers.

Amy is a magnificent geek and almost 10 year veteran of server administration and software development. She has worked at IBM, Concurrent Technologies Corporation, and University of Pittsburgh Medical Center. Currently, she is doing custom SharePoint development connected with Team Foundation Server and the ASP.NET MVC framework development using the Entity Framework, C#, and jQuery. She is currently living in Pittsburgh and not happy at all about commuting into a city with 3 rivers because of the many bridges and no serious commuter subway systems… Who plans this stuff?

Welcome Amy!

Data Annotations, MVC, and Why You Might Like Them

So if you were like me before I knew what Data Annotations were, you most likely would be thinking, “What are Data Annotations?”. Well I’m glad I can read your mind and therefore I am glad you asked.

Now the fun part about this post is that I might have to admit I was wrong. Why would that be? Well in this post I suggested that validation rules would be set in the controller. Turns out, there is possibly a better place, on the model itself. How can this be done??? Well that’s what you’re about to find out.

Say you have a user create model:

  public class AddUserModel
    public String UserName { get; set; }
    public String Password { get; set; }
    public String RepeatPassword { get; set; }

Now you could have a method on the controller like:

  public ActionResult AddUser(AddUserModel model)

Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them…) Or you can have this:

  public ActionResult AddUser(AddUserModel model)

And that is already built in so no validation method needed. But how is that possible? Attributes on the model or namely the ValidationAttribute class.

First off you have to include the System.ComponentModel dll in the project. Simple enough. Please say you know how to do that or do me a favor and remind yourself to blink. OK done? Good.

Now you can use some of the built in attributes which is good. Things like required are nice:

  public class AddUserModel
    public String UserName { get; set; }

There you go. Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:


Now you might wonder what the error message will be for that? Honest answer: I have no f–king clue. That’s why you can actually set it. Those guys at Microsoft thought of everything.

  public class AddUserModel
    [Required(ErrorMessage = "ENTER A USERNAME IDIOT!"]
    public String UserName { get; set; }

The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn’t use the one above. Whatever.

Now you might want to actually pass the errors back, and why wouldn’t you? You’re a fine, upstanding, and thoughtful person and I lie like a crook. The errors, if there are any, are in here:


And you can use two loops to get to all of them, but I think the parent loop will only run once.

  foreach (ModelState state in ViewData.ModelState.Values)
    foreach (ModelError error in state.Errors)

Pretty nice huh? Maybe if you’re an idiot who just learned about this. For cool people like me, it’s old news.

What’s the point this? If “this” is data annotations: Well it helps move some of the validation off the controller if you are looking for a more “Fat model, skinny controller” design which I’m told is a good idea. This also gets rid of all the validation methods and saves time because of it.

If “this” is your life? I have no idea. But if you’re to the point that you’re asking me about the meaning of your life, you are in some serious trouble.

ASP.Net MVC: Quick Overview of Controller Structure

Wow, that’s a mouthful far as titles go, but couldn’t think of a better way to say it. Now what I’m about to go through is the “system” I have found that works pretty well when it comes to structuring controllers knowing that there will be asynchronous operations. Why is that a big deal? Well where you put certain methods can depend on which controller actually owns the action.

When I started using MVC, I had some issues on figuring out how to build controllers so that they made sense from a structural point of view. I slightly touched on it but I wanted to show where I progressed to in the vain hope that I can help prevent stumbling on your part.

One thing to be noted is the asynchronous part. I’ve become a firm believer that MVC is pointless without asynchronous operations. Why? Simply put, you can use them or you can come up with some annoying post and redirect for any create, update, or delete operations. If you’re going to do that, you might as well just be institutionalized because you are one masochistic mother f—er. For everyone else in the happy world, go with something like jQuery that makes it real easy to perform said operations.

With the last paragraph in mind, the part I had trouble with the most was figuring out where the actions go. You see, when I started using MVC, I grouped stuff in an ultra simple manor. Say I have a site for handling pictures. Well there would be a view controller that would have anything to do with viewing images and an admin controller that took care of the uploading, changing, deleting, ecting. As you can imagine, this was not what you might call ideal.

Once I got a feeling for MVC and how it worked, I started having things a little more separated but still didn’t feel right. I had actions for viewing a list of images on the image controller no matter if public or admin side which wasn’t really ideal to me since it kind of blurred what was public and what was restricted from a conceptual point of view.

It wasn’t until I started thinking in terms of unit testing that it started to make more sense. If I were creating controllers as if they were classes instead of pages like with WebForms, maybe it would work out better. Seems real profound right? Well it was at the time since I still had WebForms state of mind. All of a sudden, it made way more sense on how the controllers should be set up. In an odd way, the controllers almost became almost business layer like. If I wanted to update an Image, there would be an Update method on the image controller responsible for taking in the changes, validating, and dealing with the entity objects. Everything that had to do strictly with displaying information would be handled by a display controller like the before mentioned Admin controller. So something like:

Controller Outline

As you can see, the Admin controller has something to show all users. The User controller has the methods for things like updating, creating, and validation. Basically anything that would change an image is on one controller. Anything for showing it on the main section controller. That is, a controller that embodies an overall concept like say an Admin section of a site or possibly a controller for viewing galleries.

The sequence of events (bad word choice…) would be something like:

Open Admin/UserList/
Admin controller uses User Entity to retrieve list
Admin View shows User List
User clicks delete button/link on Admin View
Javascript/jQuery method invoked to send id to User/Delete
User controller receives id
User controller validates id to make sure it is valid
User controller validates current user to see if allowed to delete
User entity Delete method invoked by User Controller
Result of Delete Method is returned by User Controller (JSon preferably)
Admin View displays the result

Treating controllers like classes (and the use of anonymous actions) allows a very clean separation of actions resulting in a nice logical layout. Beyond this, it also allows for a greater separation between controllers which means its possible to do multiple parts of the entire project in parallel.

Maybe this is just stating the obvious, something I’m pretty good at, but my hope was to give a quick over view of laying out controllers for those who are just starting out.

ASP.Net MVC: Attibute to Check if Route Value Exists and… and Means Something!

Get ready for a roller coaster ride around the insanity that is me. You might actually find it amusing but most likely you’ll just leave sick or underwhelmed. Don’t feel bad if you do, you wouldn’t be the first and, thanks to somehow being impervious to Natural Selection, you won’t be the last. Be proud.

Here’s what this post is about: Say you have a url like eh:


Where 1 represents a UserId to a user that exists in some matter of context. (Does that makes sense?) Well there are a couple of things that could go wrong here. For one, if you don’t want to have a nullable id in your signature:

  public ActionResult View(Int32? userId)

This could cause ouch:


But this problem is deeper. Much deeper. In fact so deep it deeper than even Piper Perabo has ever deeped before. Yrraaaahh!

What if the id doesn’t even refer to anything? Say the id is 101 but there’s no user with the id of 101? Beyond that, what if the id could be Id in some routes but UserId in others? WHAT WOULD YOU DO???

The idea here is to have something neato like this:

  public ActionResult View(Int32 userId)

And if that id is junk, then you redirect to an error page. Well if this sounds interesting, I’d be surprised, but read on in the event that it does.

Now this isn’t accomplished in the most simple manor, but for good reason: The more time in means the less time repeating. First method we need is something to simply check the route data to see if something exists:

  public static Boolean RouteDataValueExists(ActionExecutingContext filterContext, String idToCheck)
    return filterContext.RouteData.Values.ContainsKey(idToCheck);

Real easy. It either has been digested by MVC and regurgitated into some kind of route value or it hasn’t. Basically this is the first check. After all, if it doesn’t exist why bother going further?

Next is the method that will be calling this one. Mainly one that uses the RouteDataValueExists and if returns true, then it actually checks the value against where ever the user is persisted.

  public static Boolean ValueFoundAndItemExists
    ActionExecutingContext filterContext,
    Enum idToUse,
    Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,
    Func<Int32, Boolean> exists
    Boolean checksOut = false;
    String convertedId = idToUse.ToString();

    if (RouteDataValueExists(filterContext, convertedId))
      checksOut = check(filterContext, idToUse, exists);

    return checksOut;

Ok so kind of a lot at first and it’s hard to decide how to present this system, so just go with it.

  Enum idToUse,

This is a design choice. In reality this will be turned into a string anyhow, but the idea is it will be what to check the route values for. So if you are checking for UserId, you will pass in UserRequestTypes.UserId. Again this was a choice on my part as I hate passing text around.

  Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,

This is the method that will be used by ValueFoundAndItemExists to delegate out the actual checking if the id is an integer and is a real user.

Func<Int32, Boolean> exists

This will be the method that you will use to delegate the whole checking if it exists in the database. Something like:

  class User
    public Exists(Int32 id)
       return EntityContext.Context.User.Any(user => user.Id == id);

Still with me? No? Greeeeat. Next up is the base class that contains the

  Func<ActionExecutingContext, Enum, Func<Int32, Boolean>, Boolean> check,

parameter from above.

public abstract class BaseExistsAttribute : ActionFilterAttribute
  protected Boolean Exists
    ActionExecutingContext filterContext,
    Enum idToUse,
    Func<Int32, Boolean> exists
    Int32? id = Convert.ToString(filterContext.RouteData.Values[idToUse.ToString()]).ConvertTo<Int32>();
    return id.HasValue && exists(id.Value);

Ok so something might look familiar like well basically all the parameters. The reason for this is that there is a little bit of delegate passing going on with this whole system. One method passes on methods to other method in some kind of crazy method hoe down without the flanel shirts.

You will notice the use of the enum in this part:


Again, you can easily just pass in a string instead of an enum, I just did this to stay away from strings.

Only thing that might be of interest is the ToConvert method that you can find here. You don’t have to use it, you can simply just do a try parse on the


To get an integer. That’s up to you. I could have just put that in the code for you to see but then I couldn’t randomly plug another post of mine.

Finally you have the actual attribute class:

  public class QuoteExistsByQuoteId : BaseExistsAttribute
    public override void OnActionExecuting(ActionExecutingContext filterContext)

        filterContext.Result = SiteMethods.ErrorOut(ErrorNames.General_PageError);

And now it all comes together.


This is the enum I’ve been talking about this entire post! Now that I think of it, not really exciting.


That’s the method on the base class that checks for everything.


And that’s the method I need to check the persistence if the user is real. Remember? Takes in an integer and returns a boolean? Yes? Yes? No?

What’s ErrorOut? Again this is just a method I made to create an ActionResult that is an redirect to an error page. Not hugely important. It’s just what handles the situation when the value is bogus…. dude.

  public ActionResult View(Int32 userId)

And there you have it. Hopefully it was useful in some way but I’m not of touch with reality.

ASP.Net MVC HtmlHelper Method for Creating Buttons With Forms and Optional Images: Part 1

Straight from the “I made this and maybe you can find a use for it” bin, here is one of two ways I create image buttons. Why would you care? I have no idea, but two of the catches that comes with buttons is they have to be wrapped in a form and the fact you have to, far as I know, add hidden value inputs to the form to carry over the values from a url (Action of the form). This take care of both, can ya’ belee it?

This guy takes in a url (ie you already know what it should be, say from pre determined redirect value), breaks down the url to get the request parameters to make hidden inputs, and adds the button. Now I went with the image being a style for the button instead of passing in a location for the image itself, mostly because I find that to be easier to handle from a design perspective since it’s possible that particular image might be used a lot on a site. Seems easier, if you need to change the image, to change one css class then to have to search and replace a million image urls. But what do I know? No seriously, what do I know?

public static String OptionalImageButton(this HtmlHelper helper, String returnUrl, Boolean viewAsImage, FormMethod formMethod, String buttonText, String formClass, String imageClass, String buttonClass)
  StringBuilder html = new StringBuilder();
  //Create the form along with the formMethod passed in
  html.Append("<form action=\"" + returnUrl + "\" class=\"" + formClass + "\" method=\"" + formMethod + "\"> ");

  //This is the method from this post, it just give me all the hidden inputs from a url
  //This is where you might hate me.  Instead of having an image for the button
  //I am using a css class to hold the image.  Just a choice, makes it easier
  //in my opinion
  if (viewAsImage)
    html.Append("<input type=\"submit\" value=\"\" class=\"" + imageClass + "\" />");
    //If no image, then just put a text button.
    html.Append("<input type=\"submit\" value=\"" + buttonText + "\" class=\"" + buttonClass + " \" ></input>");

  //End the form

  return html.ToString();

You might notice the FormClass parameter, or maybe you didn’t because you can’t read. If that’s the case, then we’re both wasting time. However, if you did notice then you might find it odd. As it is, a form has to be inline in order to show buttons next to each other. After all, by default a form is a block element like a div. Therefore, the form itself will need a class or the style set. Now I could default this to inline, but for the sake of giving power to the programmer, it’s left as a parameter. After all, maybe not all buttons should be inline.

And usage:

  Html.OptionalImageButton(Model.ReturnUrl, Model.UserShowImages, "Return", "inline", "returnButton", "button080SmallTextAction")

Pretty easy to use and clean… well clean for MVC at least. Next MVC post I’ll show the route driven version of this “control”.

ASP.Net MVC: Button Post Is Losing QueryString Values And Getting Paramters From A URL

I was going to start this post with a rousing ARE YOU READY FOR SOME PROGRAMMING?, but my lawyer suggested it might cause the NFL to take action against me. He suggested something more simple like PROGRAMMING HAPPENS HERE! since he had high doubts the NBA will sue me. After all they’d have to admit they actually came up with that f-ing slogan in the first place. It’s a win/win situation for me.

So one of the things I’ve run into with MVC is this situation… Say I have a form and a button, and the form has an action that looks like this:

  <form action="/Tools/AddTool/1?redirect=/Tools/ViewTool/1" method="post">
    < button type="submit">GO!</button>

Really simple. The idea is that I want to post to the AddTool action, do some stuff, then have the action redirect back to the ViewTool action. Seems like it should be easy right? Well not so much. Because when you view the ActionParameters (Like in this example) for the “redirect” key, it finds the key but loses the value. This may result in a failure if have an attribute making sure it exists or possiblly you just have it set to a default that’s useless like a fourth foot. Either way, not good.

Now I haven’t figured out the reason for this (Don’t act so surprised, you aren’t a very good actor), but I have figured out a way around it. Basically for the form to keep the values, you need to add hidden values. I know, it’s a pain. Good thing I have a method that makes it easier. Also, this post is a prerequisite for a method I have for creating buttons… but that in the future. ITS A TEASER! THIS POST IS A TEASER! THERE I SAID IT! CAN I GO NOW?

public static String CreateHiddenValuesFromUrl(String baseUrl)
  StringBuilder html = new StringBuilder();

    //Have to find the ? to know where to begin
    Int32 indexOfQuestionMark = baseUrl.IndexOf('?');

    //If the question mark exists and there is something after it, keep going
    if (indexOfQuestionMark > -1 && baseUrl.Length >= indexOfQuestionMark + 1)
      //Get everything AFTER the ?, something I didn't think of first time around
      //Caused many test failures and much shame to my family.
      String request = baseUrl.Substring(indexOfQuestionMark + 1);

      //Cut up the string by the & since every parameter after the first
      //is divided by &.. I know, Duh.
      String[] splitList = request.Split('&');

      //Go through the list of possible request items
      foreach (var requestItem in splitList)
        String[] splitItem = requestItem.Split('=');
        //This is to make sure the parameter actually has a value to send in
        //the hidden values.  I supposed you could create an empty hidden
        //value to preserve the parameter, but remember the parameter
        //isn't being lost from the form action, just the value
        if (splitItem.Length == 2 && !String.IsNullOrEmpty(splitItem[1]))
          //Create a hidden input with the key name and the value
          html.Append("<input type=\"hidden\" name=\"" + splitItem[0] + "\" value=\"" + splitItem[1] + "\" >");

  return html.ToString();

And it’s just that simple. Mind you I could probably make this an extension method for the HtmlHelper, but I don’t really use it for that.

Next up will be more razzle and dazzle using this to make an optional image button. I bet you can’t wait. I know I can.