Friday, September 13, 2013

Konsumsi data JSON Pada ASP.NET MVC 4 & Jquery Secara Realtime

Controller
1:   //Controller membuat Json ke String untuk membuat variable/paremeter Object Json ke Html  
2:      public ActionResult DataGrade()  
3:      {  
4:        var client = new WebClient();  
5:        client.Headers.Add("User-Agent", "Nobody");  
6:        var json = client.DownloadString(new Uri("http://localhost:7794/GetUser.svc/getJson"));  
7:        ViewBag.Json = json.ToString();  
8:        return PartialView("_PartialUserGrade");  
9:      }  
PartialView
1:  <table id="table-user" style="width:95%">  
2:    <tr><th colspan="5">Participant Grade</th></tr>  
3:    <tr><td colspan="5"></td></tr>  
4:   <tr>  
5:      <th>ID</th>  
6:      <th>Name</th>  
7:      <th>College</th>  
8:      <th>Country</th>  
9:      <th>Grade</th>  
10:    </tr>  
11:  </table>  
12:  @Scripts.Render("~/bundles/jquery")  
13:  @Scripts.Render("~/bundles/json2html")  
14:  @Scripts.Render("~/bundles/custom")  
15:  <script>  
16:    getUserAll(@Html.Raw(@ViewBag.Json));  
17:  </script>  
View : index.cshtml
1:  @{  
2:    ViewBag.Title = "Welcome IOAA";  
3:  }  
4:  @section hero {  
5:    <section class="hero">  
6:      <div class="container">  
7:        <h1>  
8:          <span class="line-one">International Olympiad of Astronomy and Astrophysics</span>  
9:        </h1>  
10:        <a href="#" class="call-button">@ViewBag.Title</a>  
11:      </div>  
12:    </section>  
13:  }  
14:  <br />  
15:  <div id="data">  
16:  </div>  
17:  <script type="text/javascript">  
18:    $(document).ready(function () {  
19:      var j = jQuery.noConflict();  
20:      j(document).ready(function () {  
21:        j("#data").everyTime(10000, function (i) {  
22:          j.ajax({  
23:            url: "/Home/DataGrade/",  
24:            cache: false,  
25:            success: function (html) {  
26:              j("#data").html(html);  
27:            }  
28:          })  
29:        })  
30:      });  
31:    });  
32:  </script>  

No comments:

Post a Comment