summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/src/System.Web.Helpers/WebGrid/_WebGridRenderer.cshtml
blob: 2c8bd8388600aa3c4740a469b42067bab09814b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
@using System.Globalization 
@using System.Text 
@using System.Web.Helpers.Resources
@using System.Web.Mvc 
@using System.Web.WebPages.Scope 
@using Microsoft.Internal.Web.Utils

@helper GridInitScript(WebGrid webGrid, HttpContextBase httpContext) { 
    if (!webGrid.IsAjaxEnabled) {
        return;
    } 
    if (!IsGridScriptRendered(httpContext)) { 
        SetGridScriptRendered(httpContext, true);
        <script type="text/javascript">
        (function($) {
            $.fn.swhgLoad = function(url, containerId, callback) {
                url = url + (url.indexOf('?') == -1 ? '?' : '&') + '__swhg=' + new Date().getTime();

                $('<div/>').load(url + ' ' + containerId, function(data, status, xhr) {
                    $(containerId).replaceWith($(this).html());
                    if (typeof(callback) === 'function') {
                        callback.apply(this, arguments);
                    }
                });
                return this;
            }

            $(function() {
                $('table[data-swhgajax="true"],span[data-swhgajax="true"]').each(function() {
                    var self = $(this);
                    var containerId = '#' + self.data('swhgcontainer');
                    var callback = getFunction(self.data('swhgcallback'));

                    $(containerId).parent().delegate(containerId + ' a[data-swhglnk="true"]', 'click', function() {
                        $(containerId).swhgLoad($(this).attr('href'), containerId, callback);
                        return false;
                    });
                })
            });

            function getFunction(code, argNames) {
                argNames = argNames || [];
                var fn = window, parts = (code || "").split(".");
                while (fn && parts.length) {
                    fn = fn[parts.shift()];
                }
                if (typeof (fn) === "function") {
                    return fn;
                }
                argNames.push(code);
                return Function.constructor.apply(null, argNames);
            }
        })(jQuery);
        </script>
    } 
} 

@helper Table(WebGrid webGrid, 
        HttpContextBase httpContext, 
        string tableStyle, 
        string headerStyle, 
        string footerStyle, 
        string rowStyle, 
        string alternatingRowStyle, 
        string selectedRowStyle,
        string caption, 
        bool displayHeader, 
        bool fillEmptyRows, 
        string emptyRowCellValue,
        IEnumerable<WebGridColumn> columns,
        IEnumerable<string> exclusions,
        Func<dynamic, object> footer,
        object htmlAttributes) {
    
    if (emptyRowCellValue == null) {
        emptyRowCellValue = "&nbsp;";
    }

    @GridInitScript(webGrid, httpContext) 

    var htmlAttributeDictionary = TypeHelper.ObjectToDictionary(htmlAttributes);
    if (webGrid.IsAjaxEnabled) {
        htmlAttributeDictionary["data-swhgajax"] = "true";
        htmlAttributeDictionary["data-swhgcontainer"] = webGrid.AjaxUpdateContainerId;
        htmlAttributeDictionary["data-swhgcallback"] = webGrid.AjaxUpdateCallback;
    }

    <table@(tableStyle.IsEmpty() ? null : Raw(" class=\"" + HttpUtility.HtmlAttributeEncode(tableStyle) + "\""))@PrintAttributes(htmlAttributeDictionary)>
    @if (!caption.IsEmpty()) {
        <caption>@caption</caption>
    }
    @if (displayHeader) {
    <thead>
        <tr@CssClass(headerStyle)>
        @foreach (var column in columns) {
            <th scope="col">
            @if (ShowSortableColumnHeader(webGrid, column)) {
                var text = column.Header.IsEmpty() ? column.ColumnName : column.Header;
                @GridLink(webGrid, webGrid.GetSortUrl(column.ColumnName), text)
            }
            else {
                @(column.Header ?? column.ColumnName)
            }
            </th>
        }
        </tr>
    </thead>
    }
    @if (footer != null) {
    <tfoot>
        <tr @CssClass(footerStyle)>
            <td colspan="@columns.Count()">@Format(footer, null)</td>
        </tr>
    </tfoot>
    }
    <tbody>
    @{
        int rowIndex = 0;
    }
    @foreach (var row in webGrid.Rows) {
        string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, selectedRowStyle);
        <tr@CssClass(style)>
        @foreach (var column in columns) {
            var value = (column.Format == null) ? HttpUtility.HtmlEncode(row[column.ColumnName]) : Format(column.Format, row).ToString();
            <td@CssClass(column.Style)>@Raw(value)</td>
        }
        </tr>
    }
    @if (fillEmptyRows) {
        rowIndex = webGrid.Rows.Count;
        while (rowIndex < webGrid.RowsPerPage) {
            string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, null);
            <tr@CssClass(style)>
                @foreach (var column in columns) {
                    <td@CssClass(column.Style)>@Raw(emptyRowCellValue)</td>
                }
            </tr>
        }
    }
    </tbody>
    </table>
}


@helper Pager(
        WebGrid webGrid,
        HttpContextBase httpContext,
        WebGridPagerModes mode,
        string firstText,
        string previousText,
        string nextText,
        string lastText,
        int numericLinksCount,
        bool renderAjaxContainer) {

    int currentPage = webGrid.PageIndex;
    int totalPages = webGrid.PageCount;
    int lastPage = totalPages - 1;

    @GridInitScript(webGrid, httpContext) 
    
    if (renderAjaxContainer && webGrid.IsAjaxEnabled) {
        @:<span data-swhgajax="true" data-swhgcontainer="@webGrid.AjaxUpdateContainerId" data-swhgcallback="@webGrid.AjaxUpdateCallback">
    }

    if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && currentPage > 1) {
        if (String.IsNullOrEmpty(firstText)) {
            firstText = "<<";
        }
        @GridLink(webGrid, webGrid.GetPageUrl(0), firstText)
        @Raw(" ")
    }
  
    if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && currentPage > 0) {
        if (String.IsNullOrEmpty(previousText)) {
            previousText = "<";
        }
        @GridLink(webGrid, webGrid.GetPageUrl(currentPage - 1), previousText)
        @Raw(" ")
    }

    if (ModeEnabled(mode, WebGridPagerModes.Numeric) && (totalPages > 1)) {
        int last = currentPage + (numericLinksCount / 2);
        int first = last - numericLinksCount + 1;
        if (last > lastPage) {
            first -= last - lastPage;
            last = lastPage;
        }
        if (first < 0) {
            last = Math.Min(last + (0 - first), lastPage);
            first = 0;
        }
        for (int i = first; i <= last; i++) {
            var pageText = (i + 1).ToString(CultureInfo.InvariantCulture);
            if (i == currentPage) {
              <span>@pageText</span>
            }
            else {
              @GridLink(webGrid, webGrid.GetPageUrl(i), pageText)
            }
            @Raw(" ")
        }
    }

    if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (currentPage < lastPage)) {
        if (String.IsNullOrEmpty(nextText)) {
          nextText = ">";
        }
        @GridLink(webGrid, webGrid.GetPageUrl(currentPage + 1), nextText)
        @Raw(" ")
    }
    
    if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && (currentPage < lastPage - 1)) {
        if (String.IsNullOrEmpty(lastText)) {
          lastText = ">>";
        }
        @GridLink(webGrid, webGrid.GetPageUrl(lastPage), lastText)
    }
    
    if (renderAjaxContainer && webGrid.IsAjaxEnabled) {
        @:</span>
    }
}

@functions{
    private static readonly object _gridScriptRenderedKey = new object();

    private static bool IsGridScriptRendered(HttpContextBase context) {
        bool? value = (bool?)context.Items[_gridScriptRenderedKey];
        return value.HasValue && value.Value;
    }

    private static void SetGridScriptRendered(HttpContextBase context, bool value) {
        context.Items[_gridScriptRenderedKey] = value;
    }

    private static bool ShowSortableColumnHeader(WebGrid grid, WebGridColumn column) {
        return grid.CanSort && column.CanSort && !column.ColumnName.IsEmpty();
    }

    public static IHtmlString GridLink(WebGrid webGrid, string url, string text) {
        TagBuilder builder = new TagBuilder("a");
        builder.SetInnerText(text);
        builder.MergeAttribute("href", url);
        if (webGrid.IsAjaxEnabled) {
            builder.MergeAttribute("data-swhglnk", "true");
        }
        return builder.ToHtmlString(TagRenderMode.Normal);
    }

    private static IHtmlString Raw(string text) {
        return new HtmlString(text);
    }

    private static IHtmlString RawJS(string text) {
        return new HtmlString(HttpUtility.JavaScriptStringEncode(text));
    }

    private static IHtmlString CssClass(string className) {
        return new HtmlString((!className.IsEmpty()) ? " class=\"" + HttpUtility.HtmlAttributeEncode(className) + "\"" : String.Empty);
    }

    private static string GetRowStyle(WebGrid webGrid, int rowIndex, string rowStyle, string alternatingRowStyle, string selectedRowStyle) {
        StringBuilder style = new StringBuilder();

        if (rowIndex % 2 == 0) {
            if (!String.IsNullOrEmpty(rowStyle)) {
                style.Append(rowStyle);
            }
        }
        else {
            if (!String.IsNullOrEmpty(alternatingRowStyle)) {
                style.Append(alternatingRowStyle);
            }
        }

        if (!String.IsNullOrEmpty(selectedRowStyle) && (rowIndex == webGrid.SelectedIndex)) {
            if (style.Length > 0) {
                style.Append(" ");
            }
            style.Append(selectedRowStyle);
        }
        return style.ToString();
    }

    private static HelperResult Format(Func<dynamic, object> format, dynamic arg) {
        var result = format(arg);
        return new HelperResult(tw => {
            var helper = result as HelperResult;
            if (helper != null) {
                helper.WriteTo(tw);
                return;
            }
            IHtmlString htmlString = result as IHtmlString;
            if (htmlString != null) {
                tw.Write(htmlString);
                return;
            }
            if (result != null) {
                tw.Write(HttpUtility.HtmlEncode(result));
            }
        });
    }

    private static IHtmlString PrintAttributes(IDictionary<string, object> attributes) {
        var builder = new StringBuilder();
        foreach (var item in attributes) {
            var value = Convert.ToString(item.Value, CultureInfo.InvariantCulture);
            builder.Append(' ')
                    .Append(HttpUtility.HtmlEncode(item.Key))
                    .Append("=\"")
                    .Append(HttpUtility.HtmlAttributeEncode(value))
                    .Append('"');
        }
        return new HtmlString(builder.ToString());
    }

    private static bool ModeEnabled(WebGridPagerModes mode, WebGridPagerModes modeCheck) {
        return (mode & modeCheck) == modeCheck;
    }
}