-
Notifications
You must be signed in to change notification settings - Fork 4
x10. ASP.NET MVC
SpongeBob supports scaffolding of MVC controllers for entities in your domain model. In this section we will scaffold a new MVC controller and call it from jQuery.
PM> Scaffold Bob.MVC.Controller.For Person
This command will first of all add a generic BaseController if it does not exists already. Then the PersonController will be added and it will look like this
public partial class PersonController : BaseController<Person, PersonViewModel>
{
protected IPersonService PersonService;
public PersonController(IPersonService personService)
: base()
{
base.Service = this.PersonService = personService;
}
}
As you can see the generic MVC controller works in the same way as the generic service So if you want to add custom code in the PersonController just override the methods from the BaseController.
We need to install Ninject before using our service in our ASP.NET MVC Application. In my case I had to install Ninject for MVC4, but you might have another version.
PM> Install-Package Ninject.MVC4
This command will provide a new file (NinjectWebCommon) under App_Start. Now we need to add our mappings in the RegisterService method in the NinjectWebCommon.
To know what to register we can ask SpongeBob by writing a command in the Package Manager Console
PM> Scaffold Bob.Ninject.RequestScope
This will output all the lines to paste into the RegisterService method
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>().InRequestScope();
kernel.Bind<IPersonRepository>().To<PersonRepository>().InRequestScope();
kernel.Bind<IPersonService>().To<PersonService>().InRequestScope();
Note that you will have to add some usings to the namespaces to the interfaces, repositories and services.
A couple of samples on how to get data and add data using jQuery
//Post to PersonController
$.post('/Person/SaveOrUpdate',{Name:'Uffe', Age:22}, function(d){console.log(JSON.stringify(d))})
//Output, Age was invalid
{
"Status":200,
"Result":
{
"ValidationErrors":
{
"Age":["Age have to be between 1 - 20"]
},
"Entity":null,
"EntityViewModel":
{
"Name":"Uffe",
"Age":22,
"Id":0,
"Created":null,
"Updated":null
},
"IsValid":false
}
}
//Post to PersonController
$.post('/Person/SaveOrUpdate',{Name:'Uffe', Age:15}, function(d){console.log(JSON.stringify(d))})
//Output
{
"Status":200,
"Result":
{
"ValidationErrors":{},
"Entity":null,
"EntityViewModel":
{
"Name":"Uffe",
"Age":15,
"Id":2,
"Created":"2014-12-31 11:54:41",
"Updated":"2014-12-31 11:54:41"},
"IsValid":true
}
}
//Get from PersonController
$.getJSON('/Person/GetAll', function(d){console.log(JSON.stringify(d))});
//Output
{
"Entities":
[
{
"Name":"Uffe",
"Age":12,
"Id":1,
"Created":"2014-12-31 11:49:22",
"Updated":"2014-12-31 11:49:22"
},
{
"Name":"Uffe",
"Age":15,
"Id":2,
"Created":"2014-12-31 11:54:41",
"Updated":"2014-12-31 11:54:41"
}
],
"Status":200
}
