Created
December 26, 2012 03:02
-
-
Save corymartin/4377560 to your computer and use it in GitHub Desktop.
Extension method:
System.Web.Mvc.FormCollection#Fetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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