Question

I have a requirement to sort a table in my MVC razor UI. The table was generated using scaffolding option in MVC and bound to a model. The code looks something like below

@model IEnumerable<Avanade.Bureau.DataAccessLayer.DatabaseModel.SubscriptionType>
@{
    ViewBag.Title = "Subscriptions";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Subscriptions</h2>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Code)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr ng-repeat="table in Model | orderBy:predicate:reverse">
            <td>
                @Html.DisplayFor(modelItem => item.Code)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Subscribe", "Index", "Subscription", new { id = item.Id }, null)
            </td>
        </tr>
    }

</table>

I want to use Angularjs to do sorting.All the examples that I have seen so far taken show examples of data that is hardcoded in the view. As you can see my view is bound to the model which gets the data from the database via the controller. Could someone help.

Was it helpful?

Solution

You can do it by first initializing AngularJS data and then showing it:

@model IEnumerable<Avanade.Bureau.DataAccessLayer.DatabaseModel.SubscriptionType>
@{
    ViewBag.Title = "Subscriptions";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.8/angular-animate.js"></script>
<body ng-app ="ngAnimate">
<h2>Subscriptions</h2>
<div ng-init="data = [
     @foreach (var item in Model) {  
         <text>{id: '@item.Id' , code: '@item.Code' , description: '@item.Description' },</text>
     }
     ]">
</div>

<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Code)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Description)
    </th>
    <th></th>
</tr>
<tr ng-repeat="model in data">
    <td class="first">{{model.id}}</td>
    <td>{{model.code}}</td>
    <td>{{model.description}}</td>
</tr>
</table>
</body>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top