tags:

views:

391

answers:

2

I've created a helper, that I can pass a DateTime object to, and an identifier (string). It would then output three selects showing DD | MM | YYYY (or whichever way you wacky americans want your dates).

I'm adding a common component to the start of each select's Name.

  • dateselector-day-{identifier}
  • dateselector-month-{identifier}
  • dateselector-year-{identifier}

What I'd like, is to set a filter on the "OnActionExecuting" of the site controller parent to capture all form posts, skim for any fields starting with "dateselector-" add the three (day/month/year) fields into one variable named {identifier} and pass that along.

Yep, I'm attempting to replicate a Rails helper (date_select)...

+1  A: 

Create a custom action filter.

ActionExecutingContext.Params lets you to get posted values.

ActionExecutingContext.ActionParameters lets you to set parameters
that will be passed to controller action.

EDIT:
If i remember correctly, there was some datetime managment stuff in CodeCampServer source.
Might be worth checking.

EDIT2:
Yeah, eu-ge-ne. My mistake, I'm still kind a sleepy and didn't notice this in my code:

var request = filterContext.Controller.ControllerContext.HttpContext.Request;

But i mean .Params, not .Form because Params includes values from query string too.
More handy if HTTP uses GET.

Arnis L.
Arnis, `ActionExecutingContext` has no `Params` property. Did you mean `ActionExecutingContext.RequestContext.HttpContext.Request.Form`?
eu-ge-ne
+1  A: 

Just adding to Arnis's anwer ;) Use something like this in your filter:

var Params = filterContext.RequestContext.HttpContext.Request.Params;

var dateParts = Params.AllKeys
    .Where(x => x.StartsWith("dateselector-"))
    .Select(x => new {
        Id = x.Substring(x.LastIndexOf('-') + 1),
        Part = x.Remove(x.LastIndexOf('-')).Substring(x.IndexOf('-') + 1),
        Value = Params[x]
    }).GroupBy(x => x.Id)
    .ToDictionary(
        x => x.Key,
        x => x.ToDictionary(y => y.Part, y => y.Value)
    );

var date = String.Format(
    "{0}-{1}-{2}",
    dateParts["identifier"]["year"],
    dateParts["identifier"]["month"],
    dateParts["identifier"]["day"]
);

// UPDATED after comment
// Params.Add("identifier", date);

// You can use HttpContext.Items instead:
filterContext.HttpContext.Items.Add("identifier", date);
eu-ge-ne
This looks pretty good, but the Params is read only, so I can't seem to add...
boymc
Try `HttpContext.Items` instead. I've updated my answer.
eu-ge-ne
Doesn't seem to, ended up having to use JQuery inside the form, as deadlines loomed...
boymc