2014年6月5日 星期四

Return JsonResult in MVC

image

public ActionResult Movies()
{
var movies = new List<object>();

movies.Add(new { Title = "Ghostbusters", Genre = "Comedy", Year = 1984 });
movies.Add(new { Title = "Gone with Wind", Genre = "Drama", Year = 1939 });
movies.Add(new { Title = "Star Wars", Genre = "Science Fiction", Year = 1977 });

return Json(movies, JsonRequestBehavior.AllowGet);
}
 
 
<input name="btnGetMovies" id="btnGetMovies" type="submit" value="Get Movies">
<ul id="movieList"></ul>

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$("#btnGetMovies").click(function () {
var actionUrl = '@Url.Action("Movies", "Home")';
$.getJSON(actionUrl, displayData);
});

function displayData(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
$("#movieList").append("<li>" + response[i].Title + " " + response[i].Genre + " " + response[i].Year + "</li>")
}
}
}
</script>

沒有留言:

張貼留言