1

我想在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);
}

对不起,为了这个简洁,整晚都在工作;希望我的问题足够清楚?也很抱歉,因为这是一个新手问题,我可能可以通过几个小时的文档拖网获得,但我时间紧迫...... bleh。

4

2 回答 2

1

我相信您可以为此使用自定义模型绑定器。Scott Hanselman在这里有一篇文章描述了该过程,以将 DateTime 拆分为两个独立部分的概念为例。

于 2010-05-19T14:53:21.353 回答
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...

}

希望这应该像宣传的那样工作,祝你好运!

于 2010-05-26T00:35:58.980 回答