三、通过JQuery消费服务
我们通过ASP.NET MVC来构建Web应用,默认的HomeController定义如下,默认的Index操作仅仅是将默认的View呈现出来而已。
广州网站建设,网站建设,广州网页设计,广州网站设计
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- }
View中对用户操作的相应和对后台服务的调用都通过JQuery来完成,整个View的定义如下所示。
- <script type="text/javascript">
- $(function () {
- loadAllContacts();
- }
- )
- function loadAllContacts() {
- $.ajax({
- url : "api/contact",
- type : "GET",
- dataType: "json",
- success : function (data) { renderContactList(data) }
- }
- );
- }
- function renderContactList(contacts) {
- var html = "<table>";
- html += "<tr><th>First Name</th><th>Last Name</th><th>Phone No.</th><th>Email Address</th><th></th></tr>";
- for (i = 0; i < contacts.length; i++) {
- html += "<tr><td>" + contacts[i].FirstName + "</td><td>"
- + contacts[i].LastName + "</td><td>" + contacts[i].PhoneNo + "</td><td>"
- + "<input type=\"text\" class=\"textbox long\" id=\"" + contacts[i].Id + "\" value =\"" + contacts[i].EmailAddress + "\"/>" + "</td><td>"
- + "<a href=\"#\" onclick = \"updateContact('" + contacts[i].Id + "')\">Update</a> "
- + "<a href=\"#\" onclick = \"deleteContact('" + contacts[i].Id + "')\">Delete</a>" + "</td></tr>";
- }
- html += "<tr><td>" + "<input id=\"firstName\" type=\"text\" class=\"textbox\"/>" + "</td><td>"
- + "<input id=\"lastName\" type=\"text\" class=\"textbox\"/>" + "</td><td>"
- + "<input id=\"phoneNo\" type=\"text\" class=\"textbox\"/>" + "</td><td>"
- + "<input id=\"emailAddress\" type=\"text\" class=\"textbox long\"/>" + "</td><td>"
- + "<a href=\"#\" id=\"add\" onclick=\"addContact();\">Create</a> " + "</td></tr>";
- html += "</table>";
- $("#contacts").html(html);
- $("table tr:odd").addClass("oddRow");
- }
- function deleteContact(id) {
- $.ajax({
- url : "api/contact/" + id,
- type : "DELETE",
- success : function () { loadAllContacts();}
- });
- }
- function updateContact(id) {
- var emailAddress = $("#" +id).attr("value");
- $.ajax({
- url : "api/contact/" + id,
- type : "GET",
- success : function (contact) {
- contact.EmailAddress = emailAddress;
- update(contact);
- }
- });
- }
- function update(contact) {
- $.ajax({
- url : "api/contact/",
- type : "POST",
- data : contact,
- contentType : "application/json",
- success : function () { loadAllContacts(); }
- });
- }
- function addContact() {
- var contact = new Object();
- contact.FirstName = $("#firstName").attr("value");
- contact.LastName = $("#lastName").attr("value");
- contact.PhoneNo = $("#phoneNo").attr("value");
- contact.EmailAddress = $("#emailAddress").attr("value");
- $.ajax({
- url : "api/contact/",
- type : "PUT",
- data : contact,
- contentType : "application/json",
- success : function () { loadAllContacts(); }
- });
- }
- </script>
- <div id="contacts"></div>



