Skip to content

Instantly share code, notes, and snippets.

@corymartin
Created December 26, 2012 03:02
Show Gist options
  • Save corymartin/4377560 to your computer and use it in GitHub Desktop.
Save corymartin/4377560 to your computer and use it in GitHub Desktop.
Extension method: System.Web.Mvc.FormCollection#Fetch
[HttpPost]
public ActionResult Create(FormCollection collection)
{
var username = collection.Fetch("username", "anonymous");
// username will equal "anonymous" if it was not submitted
}
// VERSUS:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
var username = collection["username"];
if (username != null)
{
username = username.Trim();
}
if (string.IsNullOrEmpty(username))
{
username = "anonymous";
}
}
using System.Web.Mvc;
namespace YourApp
{
public static class ExtensionMethods
{
/// <summary>
/// Gets a value from a FormCollection. If the value does not exist
/// then the passed `_default` will be returned.
/// </summary>
/// <param name="coll"></param>
/// <param name="name"></param>
/// <param name="_default"></param>
/// <returns>
/// The value from the FormCollection if it exists, otherwise the passed default.
/// </returns>
public static string Fetch(this FormCollection coll, string name, string _default)
{
var val = coll[name];
if (val == null) return _default;
val = val.Trim();
return string.IsNullOrEmpty(val)
? _default
: val;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment