2012-06-23 107 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