Created
February 3, 2015 06:31
-
-
Save mattslay/46629f1f645d76800c4d to your computer and use it in GitHub Desktop.
Asp.Net MVC controller pattern for typical CRUD actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace {{lcControllersNameSpace}} | |
{ | |
[Authorize] | |
public class {{lcClassPlural}}Controller : {{lcAppBaseController}} | |
{ | |
[HttpGet, Route("{{lcClassPlural}}")] | |
public ActionResult List() | |
{ | |
var model = CreateViewModel<{{lcViewModelClass}}>(); | |
model.UserIsAdmin = User.IsInRole("Administrator"); | |
var {{lcLocalBoRef}} = new {{lcBusinessObjectClass}}(); | |
model.{{lcClassPlural}} = {{lcLocalBoRef}}.GetAll{{lcClassPlural}}().ToList(); | |
return View(model); | |
} | |
/// <summary> | |
/// Navigates to an entry screen to create a new {{lcClass}} | |
/// </summary> | |
/// <returns></returns> | |
[Authorize(Roles = "Administrator")] | |
[HttpGet, Route("{{lcClassPlural}}/New")] | |
public ActionResult New() | |
{ | |
return Show(-1); | |
} | |
[HttpGet, Route("{{lcClassPlural}}/{Id}")] | |
[Route("{{lcClassPlural}}/Show/{Id}")] | |
public ActionResult Show(int? Id) | |
{ | |
var model = CreateViewModel<{{lcViewModelClass}}>(); | |
model.UserIsAdmin = User.IsInRole("Administrator"); | |
if (id == null) | |
{ | |
var errorModel = new ErrorViewModel(); | |
errorModel.Message = "Invalid {{lcClass}} ID reference passed."; | |
return View("Error", errorModel); | |
} | |
var {{lcLocalBoRef}} = new {{lcBusinessObjectClass}}(); | |
{{lcClass}} {{lcClass}} = null; | |
if (Id < 0) // Creating a new one | |
{{lcClass}} = {{lcLocalBoRef}}.NewEntity(); | |
else | |
{ | |
{{lcClass}} = {{lcLocalBoRef}}.Load(Id); | |
if ({{lcClass}} == null) | |
{ | |
var errorModel = new ErrorViewModel(); | |
errorModel.Message = "Failed to load {{lcClass}} by passed value. " + {{lcLocalBoRef}}.ErrorMessage; | |
return View("Error", errorModel); | |
} | |
else | |
model.PageTitle = "{{lcClass}} Page Title"; | |
} | |
model.{{lcClass}} = {{lcClass}}; | |
LoadSelectLists(model); | |
return View("Show", model); | |
} | |
[HttpPost, Route("{{lcClassPlural}}/Save")] | |
public ActionResult Save({{lcViewModelClass}} model) | |
{ | |
if (model.{{lcClass}} == null) | |
return View("Show", model); | |
InitializeViewModel(model); | |
model.UserIsAdmin = User.IsInRole("Administrator"); | |
{{lcBusinessObjectClass}} {{lcLocalBoRef}} = new {{lcBusinessObjectClass}}(); | |
bool new{{lcClass}} = false; | |
// Load the {{lcClass}} entity record from the database... | |
{{lcClass}} {{lcLocalEntityRef}} = {{lcLocalBoRef}}.Load(model.{{lcClass}}.ID); | |
// If we weren't able to load by the ID from page properties, then we assume we are creating a new {{lcClass}}. | |
if ({{lcLocalEntityRef}} == null) | |
{ | |
{{lcLocalEntityRef}} = {{lcLocalBoRef}}.NewEntity(); | |
new{{lcClass}} = true; | |
} | |
// Store this value as loaded from DB so we can restore it after applying values from Model Binder. | |
string _{{lcKeyField}} = {{lcLocalEntityRef}}.{{lcKeyField}}; | |
// Set the {{lcClass}} instance on <{{lcViewModelClass}}> to the loaded {{lcClass}} entity | |
model.{{lcClass}} = {{lcLocalEntityRef}}; | |
// Apply values from the page viewmodel to the loaded {{lcClass}} to apply user's changes | |
this.TryUpdateModel<{{lcViewModelClass}}>(model); | |
if (!new{{lcClass}}) | |
{{lcLocalEntityRef}}.{{lcKeyField}} = _{{lcKeyField}}; // Restore this with what we read from the DB, because we will not allow the values on the viewModel | |
// to overwrite this field. | |
{{lcLocalBoRef}}.AutoValidate = true; // Will call validate method on BO when Saving to chack for valid data | |
//-- Attempt a Save, (OnValidate method on BO will be called) | |
if (!model.HasValidationErrors) | |
{ | |
if (!{{lcLocalBoRef}}.Save()) | |
{ | |
ErrorDisplay.ShowError("Errors:"); | |
ErrorDisplay.AddMessages({{lcLocalBoRef}}.ValidationErrors); // Validation error messages added by {{lcBusinessObjectClass}}.OnValidate() method. | |
model.HasValidationErrors = true; | |
model.ToasterErrorMessage = "Error saving {{lcClass}} record!"; | |
} | |
else | |
{ | |
// Need to update the posted var data for {{lcClass}}.ID in case we have created a new {{lcClass}} so the http var will have the newly assigned ID | |
ModelState.SetModelValue("{{lcClass}}.ID", new ValueProviderResult({{lcLocalEntityRef}}.ID, {{lcLocalEntityRef}}.ID.ToString(), CultureInfo.CurrentCulture)); | |
if (new{{lcClass}}) | |
model.ToasterMessage = "New {{lcClass}} record created."; | |
else | |
model.ToasterMessage = "{{lcClass}} record updated."; | |
} | |
} | |
LoadSelectLists(model); | |
return View("Show", model); | |
} | |
public void LoadSelectLists({{lcViewModelClass}} viewModel) | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment