2012-06-23 106 views
1

在我的控制,我總是最後的東西,如:如何將函數傳遞給方法?

[HttpPost] 
public ActionResult General(GeneralSettingsInfo model) 
{ 
    try 
    { 
     if (ModelState.IsValid) 
     { 
      // Upload database 
      db.UpdateSettingsGeneral(model, currentUser.UserId); 
      this.GlobalErrorMessage.Type = ErrorMessageToViewType.success; 
     } 
     else 
     { 
      this.GlobalErrorMessage.Type = ErrorMessageToViewType.alert; 
      this.GlobalErrorMessage.Message = "Invalid data, please try again."; 
     } 
    } 
    catch (Exception ex) 
    { 
     if (ex.InnerException != null) 
      while (ex.InnerException != null) 
       ex = ex.InnerException; 

     this.GlobalErrorMessage.Type = ErrorMessageToViewType.error; 
     this.GlobalErrorMessage.Message = this.ParseExceptionMessage(ex.Message); 
    } 

    this.GlobalErrorMessage.ShowInView = true; 
    TempData["Post-data"] = this.GlobalErrorMessage; 

    return RedirectToAction("General"); 
} 

什麼,我想這樣做會是這樣的:

[HttpPost] 
public ActionResult General(GeneralSettingsInfo model) 
{ 
    saveModelIntoDatabase(
     ModelState, 
     db.UpdateSettingsGeneral(model, currentUser.UserId) 
    ); 

    return RedirectToAction("General"); 
} 

我將如何傳遞一個函數作爲參數?就像我們做的JavaScript:

saveModelIntoDatabase(ModelState, function() { 
    db.UpdateSettingsGeneral(model, currentUser.UserId) 
}); 
+0

'行動 myFunction' –

+0

''delegate'行動<>'' Func <>' –

回答

3

這聽起來像你想委託。它不是立即明顯對我的委託類型應該在這裏什麼 - 可能只是Action

SaveModelIntoDatabase(ModelState, 
    () => db.UpdateSettingsGeneral(model, currentUser.UserId)); 

SaveModelIntoDatabase是:

public void SaveModelIntoDatabase(ModelState state, Action action) 
{ 
    // Do stuff... 

    // Call the action 
    action(); 
} 

如果你希望函數返回的東西,用一個Func;如果你需要額外的參數,只需添加它們作爲類型參數 - 有ActionAction<T>Action<T1, T2>

如果你是新來的代表,我強烈建議之前在C#中更大的進展變得更加熟悉他們 - 它們非常方便,是現代慣用C#的重要組成部分。有很多關於他們在網絡上,包括:

+0

我唯一使用委託的方式是在Windows應用程序下使用事件......從來沒有想過我可以輕鬆地在ASP.NET中執行相同的操作:/ ...將首先閱讀有關它們的內容,感謝指出它。 – balexandre