In my controller, I always end up with something like:
[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");
}
and what I would like to do would something like:
[HttpPost]
public ActionResult General(GeneralSettingsInfo model)
{
saveModelIntoDatabase(
ModelState,
db.UpdateSettingsGeneral(model, currentUser.UserId)
);
return RedirectToAction("General");
}
How would I pass a function as a parameter? Just like we do in javascript:
saveModelIntoDatabase(ModelState, function() {
db.UpdateSettingsGeneral(model, currentUser.UserId)
});
It sounds like you want a delegate. It’s not immediately obvious to me what your delegate type should be here – possibly just
Action:Where
SaveModelIntoDatabasewould be:If you want the function to return something, use a
Func; if you need extra parameters, just add them as type parameters – there’sAction,Action<T>,Action<T1, T2>etc.If you’re new to delegates, I’d strongly suggest getting much more familiar with them before going much further in C# – they’re really handy, and an essential part of modern idiomatic C#. There’s a lot on the web about them, including: