views:

53

answers:

2

I would like to strip out non-numeric elements from the POST data before using UpdateModel to update the copy in the database. Is there a way to do this?

// TODO: it appears I don't even use the parameter given at all, and all the magic
// happens via UpdateModel and the "controller's current value provider"?
[HttpPost]
public ActionResult Index([Bind(Include="X1, X2")] Team model) // TODO: stupid magic strings
{
    if (this.ModelState.IsValid)
    {
        TeamContainer context = new TeamContainer();

        Team thisTeam = context.Teams.Single(t => t.TeamId == this.CurrentTeamId);
        // TODO HERE: apply StripWhitespace() to the data before using UpdateModel.
        // The data is currently somewhere in the "current value provider"?
        this.UpdateModel(thisTeam);
        context.SaveChanges();

        this.RedirectToAction(c => c.Index());
    }
    else
    {
        this.ModelState.AddModelError("", "Please enter two valid Xs.");
    }

    // If we got this far, something failed; redisplay the form.
    return this.View(model);
}

Sorry for the terseness, up all night working on this; hopefully my question is clear enough? Also sorry since this is kind of a newbie question that I might be able to get with a few hours of documentation-trawling, but I'm time-pressured... bleh.

+1  A: 

I believe you can use a Custom Model Binder for this. Scott Hanselman has an article here that describes the process, using the concept of splitting a DateTime into two separate parts as an example.

Robert Harvey
+1  A: 

Instead of using the automatic model-binding in your action method's parameters, you could accept the posted FormCollection and work with that. You might be able to (1) modify the values in this special collection, then (2) bind your model manually, using UpdateModel/TryUpdateModel.

for example,

public ActionResult Index(FormCollection formCollection)
{
    DoWhateverToFormCollection(formCollection);
    Team model;
    // TO-DO: Use TryUpdateModel here and handle more nicely
    // Should also pass in binding whitelist/blacklist to the following, if didn't remove from the formCollection already...
    UpdateModel<Team>(model, formCollection);    
    // rest of your code...

}

Hopefully this should work as advertised, and best of luck!

Funka