2010-05-19 34 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分成兩個獨立部分的概念作爲例子。

相關問題