Click here to Skip to main content
15,895,841 members
Articles / Web Development / ASP.NET

MVC JavaScript Injection

Rate me:
Please Sign up or sign in to vote.
4.54/5 (4 votes)
16 Oct 2012CPOL3 min read 45.9K   740   14  
A way to inject JavaScript code in Razor.
@Styles.Render("~/Content/jqGrid/css")

@{
    ViewBag.Title = "Index";
}

<div class="ui-corner-all floatLeft" style="margin-left:2%; width:96%;">
    <select id="tableSelect">
        <option value="" disabled selected>- select table-</option>
    </select>

    <div id="grid_wrapper">
        <table id="list" class="scroll"></table>
        <div id="pager" class="scroll" style="text-align: center;"></div>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqGrid")
}

<script type="text/javascript">
    $(function () {
        var action = './Test/LoadTableNames';
        $.get(action, 'html', function (retval) {
            var arr = retval.split('*');
            for (i = 0; i < arr.length; i++) {
                $('#tableSelect').append(new Option(arr[i], arr[i]));
            }
        });

        $("#tableSelect").change(function () {
            $("#list").jqGrid("GridUnload");
            var tableName = $("#tableSelect option:selected").val();
            var action = './Test/InjectScript?tableName=' + tableName;
            $.get(action, 'html', function (retval) {
                try {
                    eval(retval);
                    $("#list").setGridParam({ url: './Test/LoadGridData?tableName=' + tableName, page: 1 }).trigger("reloadGrid");
                } catch (e) {
                    alert(e);
                }
            });
        });
    });
</script>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions