My first exploration of using MVC with the dojo toolkit focused on GETting data from a Controller.
I created a simple ServiceController, and added a ListEmployees method. In MVC, this relates to a Url like http://localhost/mvcajax/Service/ListEmployees. I added the AcceptVerbs attribute to restrict this action to GET's. Code is below:
[AcceptVerbs("GET")] public ActionResult ListEmployees() { List<Employee> emps = new List<Employee>(); emps.Add(new Employee("Dave",37)); emps.Add(new Employee("Kai", 2)); return Json(emps, "text/json-comment-filtered"); }
As you can see, this just creates two "employees", adds them to a strongly typed list, and returns them as Json. Super simple.
In the View, I wired things up using dojo.xhrGet, and then converted the json into an array of objects.
What's nice about this is that the json that's returned is automatically turned into objects.
<script type="text/javascript"> function GetEmployeesMVCGet(){ var responseNode = dojo.byId("responseMVCGet"); dojo.xhrGet({ url: '<%= Page.ResolveClientUrl("~/Service/ListEmployees") %>', handleAs: 'json', timeout:3000, contentType: "application/json; charset=utf-8", load: function(person,args){ responseNode.innerHTML ="Response: " + person[1].Name + " " + person[1].Age; }, error: function(error,args){ alert(error); responseNode.innerHtml("Error!",error); } }); } </script>
You may notice that the url passed into xhrGet looks a little funky - well, this code was copied from the View in Visual Studio, so the <%= Page.ResolveClientUrl("~/Service/ListEmployees") %> has not been evaluated. When the page is served, this expression is evaluated, and the full url added in. This is much better than putting in the path manually, as it can be used the same way from any view.
So, this is very usable, and relatively easy to build and consume
Next up - posting Data with dojo.xhrPost...
I'm Dave and this is my blog. I'm usually writing about .NET Software Development, ArcGIS, or Agile Practices, but other stuff does creep in from time to time. I hope you find something of use, and feel free to contact me if you have any questions. You can also check out my profile on LinkedIn
dojo.DTSAgile.com is our technology preview / demo site. As I and my team cook up cool things we post them here.
ArcDeveloper.net is a site that hosts a set of open source projects related to ArcGIS. This includes Tile Cache for .NET (TC4N) and Feature Server for .NET (FS4N). Come over and check it out!
Assembla is a free service that provides Subversion source control, wikis and work Tracking. The ArcDeveloper project is run from here. It rocks. Check them out today.
Agilistas is a LinkedIn group focused on discussing and promoting Agile practices. Everyone is welcome to join in the conversation as we evolve the process of creating software to make it more enjoyable for all involved.