Art Of Programming

musings by Dmytrii Nagirniak

ASP.NET MVC Request ValueProviderResult: AttemptedValue or RawValue

I want to write a small helper to obtain an object from the request. Nothing special except to note that there are AttemptedValue and RawValue properties of ValueProviderResult. Which one should I use for this helper keeping in mind that an ID of an object is always a string. Let’s see what these props are:
  • RawValue - first of all this is not always a string.

    • If it comes from RouteData it can be something else (int).
    • If it comes from Request.Form - it may be array of something (ints).

  • AttemptedValue - is just a RawData converted to string using (Convert.ToString with culture info). But in case it is obtained from Request.Form it is just a poor value of the posted data.
So just keep it in mind. For my purpose using AttemptedValue looks a bit more logical, so here’s the method on my controller:
TObject GetObjectFromRequest<TObject>(string name) where TObject: class, ILoopBack {
    var vpr = ValueProvider.GetValue(name);
    if (vpr == null)
        return null;
    return WorkSpace.GetObject<TObject>(vpr.AttemptedValue);
}

Usage sample:
public ActionResult DoSomething(MyObject obj) {
  obj.Parent = GetObjectFromRequest<MyParentObject>("parent");
  return View(); // Or whatever
}

Comments