ASP.NET MVC的cshtml頁面上,使用AngularJs搜尋資料
public ActionResult Index()
{
return View();
}
// 使用電影名稱撈取資料
public ActionResult SearchByName(string name)
{
// 使用JsonResult轉Json時,如果有日期格式,則會變成 /Date(695573315098)/ 的格式,因為EF不支援ToString(),只好先ToList(),再對日期格式做ToString()
var query = _db.Video.Where(x =>
x.Name.Contains(name)).ToList().Select(x => new { x.Name, x.ENName, ReleaseDate =
x.ReleaseDate.Value.ToString("yyyy/MM/dd") }).ToList();
return Json(query,JsonRequestBehavior.AllowGet);
}
Index.cshtml:
(angular.module已經在 _Layout.cshtml 裡設定)
<script>
myApp.controller('MovieCtrl', function ($scope, $http) {
$scope.message = 'find movie by name';
$scope.find = function (n) {
$http.get('@Url.Action("SearchByName","Movie")?name=' + n).success(function (data) {
$scope.movies = data;
});
};
$scope.orderBy = function (col) {
$scope.order = col;
};
});
</script>
<div data-ng-controller="MovieCtrl">
<h2>{{message}} : {{name}}</h2>
<input data-ng-model="name" type="text" class="input-medium
search-query" />
<button class="btn" data-ng-click="find(name)">go</button>
<table class="table
table-bordered">
<tr><td data-ng-click="orderBy('Name')">name</td><td data-ng-click="orderBy('ENName')">english name</td><td data-ng-click="orderBy('ReleaseDate')">上映日期</td></tr>
<tr data-ng-repeat="movie in movies |
orderBy:order">
<td>{{movie.Name}}</td><td>{{movie.ENName}}</td><td>{{movie.ReleaseDate}}</td>
</tr>
</table>
</div>
沒有留言:
張貼留言