2010-05-19 32 views
1

我想从POST数据中去除非数字元素,然后使用UpdateModel来更新数据库中的副本。有没有办法做到这一点?在ASP.NET MVC UpdateModel发生之前,我可以对POST数据执行一些处理吗?

// 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); 
} 

对不起,为了这个简单的工作,希望我的问题很明显吗?也很抱歉,因为这是一个新手问题,我可能能够用几个小时的文档 - 拖网捕获,但是我有时间压力...呃。

回答

1

您可以接受发布的FormCollection并使用它来代替在动作方法的参数中使用自动模型绑定。您可以(1)修改此特殊集合中的值,然后(2)使用UpdateModel/TryUpdateModel手动绑定模型。

例如,

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... 

} 

但愿这应该工作为标榜,和好运!

1

我相信你可以使用一个定制型号活页夹为此。 Scott Hanselman has an article here描述了这个过程,使用将DateTime分成两个独立部分的概念作为例子。

相关问题