Double Input problem with CheckBoxFor in MVC while serializing

if you have tried to serialize a CheckBoxFor from MVC to JSON, you will notice that you get two inputs, and it can mess up the data you are sending

It's no surprise that JavaScript is not sure how MVC works so when you try data.serialize() on MVC form data, you get odd results. Here is a simple workaround for when you need something to be serialized. I modified the GetPropertyName method from this post on StackOverflow.
public static string GetPropertyName<TModel, TValue>
    (Expression> exp)
    MemberExpression body = exp.Body as MemberExpression;
    if (body == null)
        UnaryExpression ubody = (UnaryExpression)exp.Body;
        body = ubody.Operand as MemberExpression;
    return body.Member.Name;

public static MvcHtmlString CheckBoxForJson<
    TModel, TValue>(this HtmlHelper<TModel> helper, 
    Expression<Func<TModel, TValue>> expression)
    string propName = GetPropertyName(expression);
    string html = "<input type=\"checkbox\" name=\"" 
        + propName + "\" id=\"" 
        + propName + "\" value=\"true\" />";
    return MvcHtmlString.Create(html);

And use it like this:
@Html.CheckBoxForJson(x => x.SomeBool)

The reason for the 'true' is because otherwise it will always pass as false since 'on' is not a bool value (html default).

MVC Html Helper for including an Id with a DisplayFor

there are cases when you want to include an id with your DisplayFor()

public static MvcHtmlString DisplayWithIdFor(
    this HtmlHelper helper, 
    Expression> expression, 
    string wrapperTag = "div")
    var id = helper.ViewContext.ViewData.TemplateInfo
    return MvcHtmlString.Create(
        string.Format("<{0} id=\"{1}\">{2}", wrapperTag, 
        id, helper.DisplayFor(expression)));

It is used like this:
@Html.DisplayWithIdFor(x => x.Name)
<!-- to produce -->
<div id="Name">Bill</div>

Or if you want to wrap it in a non-div:
@Html.DisplayWithIdFor(x => x.Name, "span")
<!-- to produce: -->
<span id="Name">Bill</span>

Using a Custom Controller Class in Asp.Net MVC to Simplify Coding

Controllers often have some repetitive code, implementing your own Controller class can help eliminate a lot of this

Here is a small snippet and how I use some simple tricks to help clean up my Controllers in Asp.Net MVC (using MVC 4 at the moment):
public class MyController : Controller
    public MyEntities Db { get; set; }

    protected override void OnActionExecuting(
        ActionExecutingContext filterContext)
        if (filterContext.IsChildAction)
        this.Db = new MyEntities();

    public ActionResult Index(FormCollection form)
        string srch = form["Search"] ?? string.Empty;
        return RedirectToAction("Index", 
            new { search = srch });

    protected void AttachToDb(EntityObject obj, 
        bool save = false, string entityKeyField = "Id")
            obj.EntityKey = new EntityKey(
                obj.ToPluralizedString(), entityKeyField, 
                .GetValue(obj, null));
                obj, System.Data.EntityState.Modified);
            if (save) Db.SaveChanges();

The first thing in the code is simple declaration of an EntityContext - this is implemented directly, but could (and usually should) be implemented differently for dependency injection, but you get the idea. Here is where I also like to include stuff that is often used and could be vital (and centralized) for an application like an output type for web services (JSON, XML, etc.).

Next the OnActionExecuting is over-ridden and the Context is initialized. Here is where you can initialize the properties you set above.

The next method, the HttpPost Index method is just an example of how often times you can consolidate a commonly used method. For this example, it was from an application that had searches on all index pages. Instead of repeating this code in every controller, you can just put it here.

The final method has become very useful. A use I often find, is when taking in a large model after an Asp.Net MVC POST event, I can attach the model to the Db generically without any extra work

This method is a bit confusing, but it is simply attaching the new model to the Db without a Db lookup. In my tables, I generally have a field 'Id' that houses the Primary Key of every table, whether it is an Int or Guid. This way, I can simply pass in whatever object I am currently working with, and by using the pluralize method, and reflection, the method can figure out which table to attach the model to - eliminating the need for me to do extra coding. Alternatively, if I want to change the Key from 'Id', I can pass that in as well.

Now when I get a model being POSTed, it is easy to deal with:
public ActionResult Edit(Widget model)
        AttachToDb(model, true);
        //do stuff
    else { /*do other stuff*/ }

This avoids the need to take another trip to the DB, change the properties on the object, then submit - streamlining the process very much and cutting down a lot of code.

This would be an example of how this would be done manually with the normal Controller class:
public ActionResult Edit(Widget model)
        MyEntities db = new MyEntities();
        Widget w = db.Widgets.Single(x => x.Id == model.Id);
        w.Name = model.Name;
        w.Serial = model.Serial;
        //do stuff
    else { /*do other stuff*/ }

Not a huge difference when you are just getting 2 values, but you could see how a model with 20 or 30 fields can be cut down from 30+ lines to just 1 or 2.

Constraining Routes in MVC to an Enum the Easy Way

simple way to constrain a route to only allow enum values

Say I have the following enum:
public enum SearchType { Facilities, Courses, Exercises};

And I only want those the be available in route Search/{SearchType}. I could constrain it manually with a string, but then what if the enum changes and I have this in a bunch of routes? Here is a simple way to accomplish this constraint:
public static void RegisterRoutes(RouteCollection routes)
    List searchTypeL = new List();
    foreach (Enums.SearchType type in 
    { searchTypeL.Add(type.ToString()); }
    string searchTypes = string.Join("|", searchTypeL);
        new { controller = "Search", action = "Index" },
        new { type = searchTypes }

Very basic, all this does is enumerate through your enum and create a simple string to filter with.

ReCaptcha - Getting the Challenge Key and/or image with Asp.Net MVC

Often times you do not need the whole deal, or you are working with a technology that doesn't employ javascript or iframes

Recently I was working on a project that needed to provide (via MVC 3) the ReCaptcha image and/or challenge key only, and not the whole html/javascript portion due to limitations by the data consumer. It took me a while, but there is quite an elegant and simple solution to this.

Here is the controller I came up with:
public class CaptchaController : Controller
    public string contentReturnType = "text/plain";
    public string googleChallengeUrl = "http://{0}";
    public string googleImageUrl = "http://{0}";
    public string googleImageHtml = "<img style=
        \"display: block; \" height=\"57\" width=\"300\" 

    public ContentResult GetChallengeKey(
        string proxyIpAndPort = null)
        string http = string.Format(googleChallengeUrl, 
        WebClient client = new WebClient();

        //assuming no proxy on a local machine
        if (!string.IsNullOrEmpty(proxyIpAndPort) && 
            client.Proxy = 
                new WebProxy(proxyIpAndPort, true);

        string html = client.DownloadString(http);
        int start = html.IndexOf('{');
        int length = html.IndexOf('}') - start + 1;
        string json = html.Substring(start, length);

        ReCaptchaState state = 
            new JavaScriptSerializer()
        return this.Content(state.challenge, 

    public ContentResult GetImageUrl()
        return this.Content(string.Format(googleImageUrl, 
            GetChallengeKey().Content), contentReturnType);

    public ContentResult GetImageHtml()
        return this.Content(string.Format(googleImageHtml, 
            GetImageUrl().Content), contentReturnType);

This is using json deserializing of the ReCaptcha return string into a .Net object named ReCaptchaState which is covered here.

Now all that you need to do is call one of the urls to get the desired result in a plaintext format (you can change the output if you wish).

Adding Custom Exception Handling Attributes to Your Asp.Net MVC Actions

Attributes are a simple way to run common handling across many actions without repeating yourself

I ran into a position where I was handling exceptions and pushing them to xml ContentResults the same way on multiple actions across many controller repeating a lot of code. I was working on a REST interface that always was to return xml. All Exception were to be returned in xml as well. I found myself writing a lot of actions like this:
public ContentResult Fidget()
        //do a bunch of stuff
        //throw exceptions if I need to
    catch(Exception ex) //now catch them and display xml
        // turn the exception into xml
        return this.Content(myXmlException, "text/xml");
    // if it made it here, return success xml
    return this.Content(successXml, "text/xml");

This worked great, but after a bunch of actions, the code was very redundant. I want to handle exception the same on a lot of actions, but not all, so I decided to go to an Attribute, specifically ActionFilterAttribute and the IExceptionFilter. If I override the OnException, I can automatically handle the Exceptions in the painted actions, so this is what I came up with:
public class XmlExceptionAttribute : 
    ActionFilterAttribute, IExceptionFilter
    public void OnException(ExceptionContext 
        if (filterContext.Exception == null) return;
        filterContext.ExceptionHandled = true;
        var response = filterContext.Controller
        response.ContentType = "text/xml";
        response.Write((new Status(

*Note that the Status object is a just an object I made to be serializeable and .ToXmlString() is an extension method I came up with a while back to convert objects into xml strings on the fly.

Now, if the attribute is applied, all I have to do for the above behavior in an action is simply this:
public ContentResult Fidget()
    //do a bunch of stuff, throw exceptions if I need to
    // if it made it here, return success xml
    return this.Content(successXml, "text/xml");

The behavior is now the EXACT same!

Learning Ruby on Rails for a .Net MVC C# Coder

quick reference for equivalent methods/approaches

I am learning RoR for a new project that requires the ability to truly run cross-platform (don't even say Mono...). That said, I love .net, but Ruby on Rails is a fantastic MVC framework. I am learning a lot about MVC programming in general and here is my contribution to others trying to learn RoR in my situation.

And yes, I know there are many more syntax options than the ones I show, but this is just a quick reference -if you want them all, check out the API.

Everything presented here will render the same html in the respective languages, as well as behave the same as data access (ORM):

stylesheet/javascript links

Asp.Net MVC
<link rel="stylesheet" type="text/css" 
 href="<%=Url.Content("~/public/stylesheets/style.css") %>"
<script type="text/javascript" 
 src="<%=Url.Content("~/public/javascripts/jquery.js") %>"
></ script>

<%= stylesheet_link_tag 'style' %>
<%= javascript_include_tag 'jquery' %>


Asp.Net MVC
<%= Html.ActionLink("View Widgets", "Index", "Widget") %>
<%= Html.ActionLink("Widget 5", "Show", "Widget",
  new {id = 5}) %>

<%= link_to 'View Widgets', widgets_path %>
<%= link_to 'Widget 5', widget_path(5) %>


Asp.Net MVC
<% using(Html.BeginForm()) { %>
 <%= Html.LabelFor(x => x.Name) %>
 <%= Html.TextBoxFor(x => x.Name) %>
 <input type="submit" value="submit" />
<% } >

<% form_for(@widget) do |f| %>
 <%= f.label :name %>
 <%= f.text_field :name %>
 <%= f.submit 'submit' %>
<% end %>

rendering partials

Asp.Net MVC
<%= Html.Partial("form") %>

<%= render :partial => 'form' %>


Asp.Net MVC
<% foreach(var widget in Model.Widgets) { %>
  <%= widget.Name %>
<% } %>

<% for widget in @widgets %>
  <%= %>
<% end %>


Asp.Net MVC
public partial class Widget { }

public class WidgetValidation
  [Required(ErrorMessage = "Name is Required")]
  [RegularExpression("[\\S]{5,}", ErrorMessage = "Min 5 chars")]
  [StringLength(30, ErrorMessage = "Max 30 chars")]
  public string Name { get; set; }

class Widget < ActiveRecord::Base
  validates_presence_of :name
  validates_length_of :name, :in => 5..30

orm data access

Asp.Net MVC (Linq-to-Sql)
var db = new MyDataContext();
var widgets = db.Widgets;
var widget = db.Widgets.SingleOrDefault(x => x.Id == 5);
var components = widgets.Components.OrderBy(x =>;

RoR (ActiveRecord)
@widgets = Widget.all
@widget = Widget.find(5)
@components = @widget.components.sort_by{|w|}

saving a model

Asp.Net MVC (Linq-to-Sql)
public ActionResult Create(Widget widget)

RoR (ActiveRecord)
def create
  @widget =[:widget])

helper methods

Asp.Net MVC
// define it:
public static string DivThis(this HtmlHelper html, string text)
  return "<div>" + text + "</div>";

<!-- call it: -->
<= Html.DivThis("hello") %>

# define it
def div_this(text)
  '<div>' + text + '</div>'

<!-- call it: -->
<%= div_this('hello') %>

temporary data

Asp.Net MVC
// set it
TempData["someKey"] = "hello"

<!-- use it -->
<%= TempData["someKey"].ToString() %>

# set it
flash[:some_key] = 'hello'

<!-- use it -->
<%= flash[:some_key] %>

That's all I have for now, hopefully I will be adding more in the near future. I think I like RoR...

ServerInfo - Easily scan a Machine/Server Farm for Information

new open-source project in Asp.Net MVC 2

More than once I have been asked what databases are on what server, if server X is running application Y or what websites server ABC is running. These are are relatively simple things to accomplish, and there are tools available to get this information, but this is an extremely simple and portable solution - all the data is kept in xml, so there is no need to install a backend.

All that it is required to get all this information is to enter ip addresses and the user has the rights to scan the machines requested.

In addition, this can keep track of all of the owners of the machines and has a GUI for running WMI Queries, which is extremely powerful if you know how to use it.

This is written with Asp.Net MVC 2, C# and xml; it requires .Net 4.0 framework. I will be updating this to MVC 3/Razor in the near future.

Inline AJAX DropDown and Text Editing with Asp.Net MVC and jQuery

including how to use a database to populate the dropdown

First thing is first, you will need to download jQuery and the Jeditable plugin (I prefer to refer to it as the Jedi-Table!). Be sure to put these references in your View (or Masterpage). Next, you have to set up a view on which to use an inline edit. I find that I often want to use this approach on tables of information. For this View, I will set it to use an IEnumerable of an Item I have called 'ItemOwner' (this is arbitrary and does not really matter). It will be a simple table that lists the Name and the Country of the owner, both of which will be editable inline. Here is the Index in my ExampleController.cs:
myDataContext db = new myDataContext();
public ActionResult Index()
    // get the info for the 'Countries' dropdown:
    ViewData["countries"] = db.Countries
        .Select(x => new SelectListItem() 
            Text = x.Name, 
            Value = x.Id.ToString() 

    // get the 'ItemOwners' I am interested in:
    var owners = db.ItemOwners.Take(3);

    return View(owners);

As you can see there, I am also pulling the countries from the database and throwing them into the ViewState - we will get to this later. Since the Country is actually a foreign key relation, the value is set to an integer which is the identity field in the database. It is also using a .ToJson() extension which takes a IEnumerable<SelectListItem> and puts it into a simple JSON string that I use which is here:
public static string 
    ToJson(this IEnumerable<SelectListItem> slis)
    string output = "{";
    if (slis != null)
        for (int i = 0; i < slis.Count(); i++)
            output += " '" + slis.Skip(i)
            .First().Value + "': '" + 
            slis.Skip(i).First().Text + "'" + 
            (i == slis.Count() - 1 ? " " : ",");
    return output += "}";

There is probably a better way to do that... but I don't know it?!

I am also pulling 3 ItemOwners from the database, I know this is silly, but it just an example. Here is how I am displaying them in the view:
        <% foreach(var owner in Model) { %>
            <td><%= owner.Name %></td>
            <td><%= owner.Country.Abbreviation %></td>
        <% } %>

Now that there is a simple table we want to make it a bit more interactive. Since we aregoing to make all of these fields editable, we need to add in a way to distinguish exactly what they are. To do that, we will need two things: the id of the item they are editing, and the type of inline editing we will be doing (i.e. dropdown or text input). So to do that, let's add in a few css classes and an identifieng ID:
<td id="name<%= owner.Id %>" class="editable text">
    <%= owner.Name %></td>
<td id="ctry<%= owner.Id %>" class="editable dropdown">
    <%= owner.Country.Abbreviation %></td>

And now add a little css to make them appear to be clickable:
{ cursor:pointer; background-color:Orange; }

Now they all look like you can click on them, so we can move on to making the click actually do something.

This is where the jQuery comes in, and it is very simple. I have made these 'helper' methods in Javascript to make all of my inline calls centrally controllable, I keep this in my sites script folder so if I change one inline edit, I change them all; it also makes for more readable Javascript on each page.
function InlineDropdown(collectionToDropDown, ajaxAddress, dropDownDataSet) {
        data: dropDownDataSet,
        type: 'select',
        indicator: 'saving...',
        tooltip: 'click to edit...',
        submit: 'Save',
        style: 'inherit',
        placeholder: 'click to edit'

function InlineTextbox(collectionToInline, ajaxAddress) {
        indicator: 'saving...',
        tooltip: 'click to edit...',
        style: 'inherit',
        placeholder: 'click to edit'

function InlineTextarea(collectionToInline, ajaxAddress) {
        type        : 'textarea',
        rows        : 4,
        indicator   : 'saving...',
        tooltip     : 'click to edit...',
        style       : 'inherit',
        submit      : 'Save',
        onblur      : 'ignore',
        placeholder : 'click to edit'

Obviously you can read all about the options on the Jeditable page, but this is how I set them. Also notice I have a InineTextarea included as well for a textarea which is not covered here but works the exact same.

Now the jQuery calls are almost trivial:
    "<%= Url.Content("~/Ajax/ItemOwner.ashx") %>"

    "<%= Url.Content("~/Ajax/ItemOwner.ashx") %>", 
    <%= ViewData["countries"].ToString() %>

What that is doing is sending the POST requests to the specified address. The POST contains a few things:
  • id - the id of the element that sent the request
  • value - the new value passed by the element
We are also passing more information there - remember that we passed both the type of field to edit and the id of the ItemOwner to edit, ie [name837] which emans we want to edit the Name field of ItemOwner 837. So we simply set up an ashx handler (which we specified above) to do the dirty work:
public void ProcessRequest(HttpContext context)
    string newValue;
        myDataContext db = new myDataContext();
        string elementId = context.Request.Form["id"];

        // since we made the first 4 of the id the 'field' whic to edit
        // we can just pull the first 4 letters for use in our switch:
        string fieldToEdit = elementId.Substring(0, 4);

        //now take anything after those 4 and it is the Id:
        int idToEdit = Convert.ToInt32(elementId.Remove(0, 4));

        // the value is simply a string:
        newValue = context.Request.Form["value"].Trim();

        // now that we have the id, get the ItemOwner from the db
        ItemOwner owner = db.ItemOwners.FirstOrDefault(x => x.Id == idToEdit);

        // after all is said and done, we will return newValue to the user so the field
        // looks as if the change has taken place (which it has)

        // using the field we pulled above, decide what to do:
        switch (fieldToEdit)
            // name is easy
            case "name": owner.Name = newValue; break;

            // since the country is an integer foreign key, we need to Convert.ToInt32:
            case "ctry":
                owner.CountryId = Convert.ToInt32(newValue);
                // now that we have recorded the value, we want to return the text to
                // the user and not the id value which would make no sense
                newValue = db.Countries.FirstOrDefault(x => x.Id == owner.CountryId).Abbreviation;
            // if it wasn't caught, something is wrong:
            default: throw new Exception("invalid fieldToEdit passed");

        db.SubmitChanges(); // save it
    // now if an exceptions were reported, the user can see what happened
    // this also inform the user nothing was saved
    // you could easily make this not reported to the user and logged elsewhere
    catch (Exception ex) 
    { newValue = "Error: " + ex.Message + " [nothing written to db]"; }

    //now return what you want in the element:

And that is all it takes.

Readable Return Urls in your MVC Urls

Don't surrender your clean, readable url to a nasty returnUrl string; keep your MVC urls readable

Asp.Net MVC projects have a great routing resource available to them; this makes for very clean and human-readable urls:


A lot of these web applications will use a returnUrl somewhere in there, this is where the problem comes in: return urls tend to be ugly and unreadable if passed in the query. Let's say I am not deleting something and want to return to the page I was at before, if I simply use a returnTo, the url looks like this:


The markup I used to get that was this:
<%= Html.ActionLink("Delete", "Delete", 
  new { Id = 15, returnTo = 
    ViewContext.HttpContext.Request.Url.ToString() })
Yes, I know you won't hard-code your Id in there, but it's an example. That works just fine, and the user will probably not care, but I do... To go to all that trouble to get nice readable urls, then spit out something that looks this ugly is sacrilege, there has got to be a better way, and there is, and it is ridiculously simple.

set up your routes

In your global.asax.cs, I just need to add 'catch-all' parameter, and make it nice and readable:
  new { controller = "Search", action = "Delete", 
    returnTo = "" },
  new { Id = @"\d+" }

What that {*returnTo} parameter does, is catch everything after '/ReturnTo/' in the url path (this excludes any querystring) - it is important to note that this also includes all of the slashes and does not convert anything into ugly '%2f' type notation.

update your markup

Now the exact same markup above outputs this nice url instead:


Better, but still a bit more than we need, we can make it look better by changing the markup slightly:
<%= Html.ActionLink("Delete", "Delete", 
  new { Id = 15, 
    returnTo = ViewContext.HttpContext.Request.Url
      .LocalPath.ToString() })

Adding in that '.LocalPath' now gives us this:


A nice, very readable url.

return to the url

The rest is pretty trivial, just return to the url:
public RedirectResult Delete(int Id, string returnTo)
    // do your magic here, then:
    return Redirect("~/" + returnTo);