Program: CWE-79
Project: CVE-2022-0159
Buggy source:
@model AdminDashboardViewModel
@using OrchardCore.ContentManagement;
@inject IAuthorizationService AuthorizationService
@inject IContentManager ContentManager
@inject OrchardCore.ContentManagement.Metadata.IContentDefinitionManager ContentDefinitionManager
@inject OrchardCore.ContentManagement.Display.IContentItemDisplayManager ContentItemDisplayManager

@{
    // Todo Create Settings for Dashboard
    var settings = new
    {
        // Default is 1, i.e. 6 columns in large screen, 3 for tablets and 1 for phones.
        // Changing Scale 2 will increase the # columns to 12 for large screen, 6 for tablets and 2 for phones.
        ColumnScale = 1
    };
}

<style asp-name="jQuery-ui" at="Head"></style>
<style asp-src="~/OrchardCore.AdminDashboard/Styles/dashboard.min.css" debug-src="~/OrchardCore.AdminDashboard/Styles/dashboard.css" depends-on="jQuery-ui" at="Head"></style>
<script asp-name="jQuery-ui" at="Foot"></script>

<div class="float-right mb-3 d-inline-flex">
    <a class="btn btn-success btn-sm  mr-1" asp-action="Index">
        @T["Close Editor"]
    </a>
    @if (Model.Creatable.Any())
    {
        <div class="dropdown order-md-1">
            <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" id="new-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                @T["Add Widget"]
            </button>
            <div class="dropdown-menu dropdown-menu-right scrollable" aria-labelledby="bulk-action-menu-button">
                @foreach (var item in Model.Creatable)
                {
                    <a class="dropdown-item add-list-widget btn-sm" href="@Url.RouteUrl(new { area = "OrchardCore.Contents", controller = "Admin", action = "Create", id = @item.Value, returnUrl = FullRequestPath })">@T[item.Text]</a>
                }
            </div>
        </div>
    }
</div>
<zone Name="Title"><h1 class="float-left">@RenderTitleSegments(T["Dashboard"])</h1></zone>
<div class="clearfix"></div>

<div id="dashboard-undo-message" class="alert alert-success alert-dismissible show d-none" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <form id="dashboard-undo-form" asp-action="Update" method="POST" class="no-multisubmit">
        @for (int index = 0; index < Model.Dashboards.Count(); index++)
        {
            <input type="hidden" id="undo_@(Model.Dashboards[index].Dashboard.ContentItemId)" name="parts[@(index)].ContentItemId" value="@Model.Dashboards[index].Dashboard.ContentItemId" />
            <input type="hidden" id="undo_@(Model.Dashboards[index].Dashboard.ContentItemId)_Width" name="parts[@(index)].Width" value="" />
            <input type="hidden" id="undo_@(Model.Dashboards[index].Dashboard.ContentItemId)_Height" name="parts[@(index)].Height" value="" />
            <input type="hidden" id="undo_@(Model.Dashboards[index].Dashboard.ContentItemId)_Position" name="parts[@(index)].Position" value="" />
        }
    </form>
    @T["Dashboard successfully updated."]&nbsp;<a href="#"><strong>@T["Undo"]</strong></a>.
</div>

<div class="dashboard-container" id="container" style="--dashboard-columns: calc( @(settings.ColumnScale) * var(--dashboard-columns-default));">
    @foreach (var dashboard in Model.Dashboards)
    {
        @await DisplayAsync(dashboard)
    }
</div>

<script depends-on="jQuery-ui" at="Foot">
    $(document).ready(function(){
        //
        var _menu = null;
        var cellSize = {
            width: 240,
            height: 240
        };

        $("#dashboard-undo-message a").on('click', function(e){
            e.preventDefault();
            $("#dashboard-undo-form").submit();
        });

        function Update(metadata)
        {
            var token = $("[name='__RequestVerificationToken']").val();
            var data = {
                __RequestVerificationToken : token,
                parts : metadata
            };
            $.post({
                url: '@Url.Action("Update")',
                data: data,
                success: function (data) {
                    $('#dashboard-undo-message').removeClass("d-none");
                },
                fail: function(){
                    $('#dashboard-undo-message').addClass("d-none");
                }
            });
        }

        function snapTo(org, val, gridSize)
        {
            var snap_X =1;
            if (org.width < val.width)
            {
                snap_X = Math.ceil(val.width/gridSize.width) ;
            }
            else
            {
                snap_X = Math.floor(val.width/gridSize.width) ;
            }

            if (snap_X === 0)
                snap_X = 1;

            var snap_Y =1;
            if (org.height < val.height)
            {
                snap_Y = Math.ceil(val.height/gridSize.height) ;
            }
            else
            {
                snap_Y = Math.floor(val.height/gridSize.height) ;
            }

            if(snap_Y ===0 )
                snap_Y = 1;
            var snap = { X : snap_X, Y: snap_Y};
            return snap;
        }

        function setUndoValues()
        {
            $(".dashboard-container .dashboard-wrapper")
                .each(function (index, value) {
                    $('#undo_' + $(value).attr('id') + '_Position').val(index);
                    $('#undo_' + $(value).attr('id') + '_Height').val(value.style.getPropertyValue('--dashboard-height'));
                    $('#undo_' + $(value).attr('id') + '_Width').val(value.style.getPropertyValue('--dashboard-width'));
                });
        }

        function getCurrentValues()
        {
            var metadata = [];
            $(".dashboard-container .dashboard-wrapper")
                .each(function (index, value) {
                    var position = index;
                    var height = $(this)[0].style.getPropertyValue('--dashboard-height');
                    var width = $(this)[0].style.getPropertyValue('--dashboard-width');
                    var contentItemId = $(this).attr("id");

                    metadata.push( {
                        "ContentItemId" : contentItemId,
                        "Position" : position,
                        "Width" : width,
                        "Height": height
                    });
                });
            return metadata;
        }

        function calculateCellSize()
        {
            var container = document.getElementById("container");
            var styles = window.getComputedStyle(container);

            var rows = styles.getPropertyValue('grid-template-rows');
            var columns = styles.getPropertyValue('grid-template-columns');

            var rowGap = styles.getPropertyValue('grid-row-gap').replace('px','');;
            var columnGap = styles.getPropertyValue('grid-column-gap').replace('px','');;
            var height = rows.split(' ')[0].replace('px','');
            var width = columns.split(' ')[0].replace('px','');

            cellSize = {
                width: width,
                height: height,
                gap : {
                    width : columnGap,
                    height : rowGap
                }
            };
        }

        var _sortable = $(".dashboard-container").sortable({
            tolerance: "pointer",
            opacity: 0.7,
            handle: ".dashboard-handle",
            placeholder: {
                element: function(currentItem) {
                    return $('<div  class="dashboard-dragdrop-placeholder"><div></div></div>')[0];
                },
                update: function (container, p) {
                    return;
                }
            },
            start: function (e, ui) {

                if(_menu != null){
                    $(document).trigger('click');
                }

                setUndoValues();

                var dahsboard = ui.item[0];
                ui.placeholder[0].style.setProperty("--dashboard-width", dahsboard.style.getPropertyValue("--dashboard-width"));
                ui.placeholder[0].style.setProperty("--dashboard-height", dahsboard.style.getPropertyValue("--dashboard-height"));

            },
            update: function (event, ui) {
                var op = $('#undo_' + ui.item.attr('id') + '_Position');
                // Only update if Position is changed
                if(op.val() != ui.item.index()){
                    var changed =  getCurrentValues();
                    Update(changed);
                }
            }
        });
        $(".dashboard-wrapper").resizable({
            handles: "s,e,se",
            helper: "ui-resizable-helper"
,
            start: function (event, ui) {
                if(_menu != null){
                    $(document).trigger('click');
                }
                setUndoValues();
            },
            resize: function (event, ui) {

                var original = {
                    width : ui.originalSize.width,
                    height: ui.originalSize.height
                };

                var updated = {
                    width : ui.size.width,
                    height: ui.size.height
                };

                var snap = snapTo(original, updated, cellSize);

                ui.helper[0].style.setProperty("--dashboard-width", snap.X);
                ui.helper[0].style.setProperty("--dashboard-height", snap.Y);

                ui.helper.css("width", (snap.X * cellSize.width) + ((snap.X -1 ) * cellSize.gap.width)  );
                ui.helper.css("height", (snap.Y * cellSize.height) + ((snap.Y -1 ) * cellSize.gap.height) );
            },
            stop: function (event, ui) {

                $(this).css("width", '');
                $(this).css("height", '');

                var original = {
                    width : ui.originalSize.width,
                    height: ui.originalSize.height
                };

                var updated = {
                    width : ui.size.width,
                    height: ui.size.height
                };

                var snap = snapTo(original, updated, cellSize);

                var ow = $('#undo_' + ui.element.attr('id') + '_Width');
                var oh = $('#undo_' + ui.element.attr('id') + '_Height');

                // Only update if values have changed
                if(ow != snap.X || oh != snap.Y)
                {
                    ui.element[0].style.setProperty("--dashboard-width", snap.X);
                    ui.element[0].style.setProperty("--dashboard-height", snap.Y);

                    var changed =  getCurrentValues();
                    Update(changed);
                }
            }
        });

        $(window).on('show.bs.dropdown', function (e) {
            _menu = $(e.target).find('.dropdown-menu');
            $('body').append(_menu.detach());
            var eOffset = $(e.target).offset();
            _menu.css({
                'display': 'block',
                    'top': eOffset.top + $(e.target).outerHeight(),
                    'left': eOffset.left
            });
        });

        $(window).on('resize', function (e) {
            calculateCellSize();
        });

        $(window).on('hide.bs.dropdown', function (e) {
            $(e.target).append(_menu.detach());
            _menu.hide();
            _menu = null;
        });
    });
</script>


Fixed version (ground truth):
@model AdminDashboardViewModel
@using OrchardCore.ContentManagement;
@inject IAuthorizationService AuthorizationService
@inject IContentManager ContentManager
@inject OrchardCore.ContentManagement.Metadata.IContentDefinitionManager ContentDefinitionManager
@inject OrchardCore.ContentManagement.Display.IContentItemDisplayManager ContentItemDisplayManager

@{
    // Todo Create Settings for Dashboard
    var settings = new
    {
        // Default is 1, i.e. 6 columns in large screen, 3 for tablets and 1 for phones.
        // Changing Scale 2 will increase the # columns to 12 for large screen, 6 for tablets and 2 for phones.
        ColumnScale = 1
    };
}

<style asp-name="jQuery-ui" at="Head"></style>
<style asp-src="~/OrchardCore.AdminDashboard/Styles/dashboard.min.css" debug-src="~/OrchardCore.AdminDashboard/Styles/dashboard.css" depends-on="jQuery-ui" at="Head"></style>
<script asp-name="jQuery-ui" at="Foot"></script>

<div class="float-right mb-3 d-inline-flex">
    <a class="btn btn-success btn-sm  mr-1" asp-action="Index">
        @T["Close Editor"]
    </a>
    @if (Model.Creatable.Any())
    {
        <div class="dropdown order-md-1">
            <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" id="new-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                @T["Add Widget"]
            </button>
            <div class="dropdown-menu dropdown-menu-right scrollable" aria-labelledby="bulk-action-menu-button">
                @foreach (var item in Model.Creatable)
                {
                    <a class="dropdown-item add-list-widget btn-sm" href="@Url.RouteUrl(new { area = "OrchardCore.Contents", controller = "Admin", action = "Create", id = @item.Value, returnUrl = FullRequestPath })">@T[Html.Encode(item.Text)]</a>
                }
            </div>
        </div>
    }
</div>
<zone Name="Title"><h1 class="float-left">@RenderTitleSegments(T["Dashboard"])</h1></zone>
<div class="clearfix"></div>

<div id="dashboard-undo-message" class="alert alert-success alert-dismissible show d-none" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <form id="dashboard-undo-form" asp-action="Update" method="POST" class="no-multisubmit">
        @for (int index = 0; index < Model.Dashboards.Count(); index++)
        {
            <input type="hidden" id="undo_@(Model.Dashboards[index].Dashboard.ContentItemId)" name="parts[@(index)].ContentItemId" value="@Model.Dashboards[index].Dashboard.ContentItemId" />
            <input type="hidden" id="undo_@(Model.Dashboards[index].Dashboard.ContentItemId)_Width" name="parts[@(index)].Width" value="" />
            <input type="hidden" id="undo_@(Model.Dashboards[index].Dashboard.ContentItemId)_Height" name="parts[@(index)].Height" value="" />
            <input type="hidden" id="undo_@(Model.Dashboards[index].Dashboard.ContentItemId)_Position" name="parts[@(index)].Position" value="" />
        }
    </form>
    @T["Dashboard successfully updated."]&nbsp;<a href="#"><strong>@T["Undo"]</strong></a>.
</div>

<div class="dashboard-container" id="container" style="--dashboard-columns: calc( @(settings.ColumnScale) * var(--dashboard-columns-default));">
    @foreach (var dashboard in Model.Dashboards)
    {
        @await DisplayAsync(dashboard)
    }
</div>

<script depends-on="jQuery-ui" at="Foot">
    $(document).ready(function(){
        //
        var _menu = null;
        var cellSize = {
            width: 240,
            height: 240
        };

        $("#dashboard-undo-message a").on('click', function(e){
            e.preventDefault();
            $("#dashboard-undo-form").submit();
        });

        function Update(metadata)
        {
            var token = $("[name='__RequestVerificationToken']").val();
            var data = {
                __RequestVerificationToken : token,
                parts : metadata
            };
            $.post({
                url: '@Url.Action("Update")',
                data: data,
                success: function (data) {
                    $('#dashboard-undo-message').removeClass("d-none");
                },
                fail: function(){
                    $('#dashboard-undo-message').addClass("d-none");
                }
            });
        }

        function snapTo(org, val, gridSize)
        {
            var snap_X =1;
            if (org.width < val.width)
            {
                snap_X = Math.ceil(val.width/gridSize.width) ;
            }
            else
            {
                snap_X = Math.floor(val.width/gridSize.width) ;
            }

            if (snap_X === 0)
                snap_X = 1;

            var snap_Y =1;
            if (org.height < val.height)
            {
                snap_Y = Math.ceil(val.height/gridSize.height) ;
            }
            else
            {
                snap_Y = Math.floor(val.height/gridSize.height) ;
            }

            if(snap_Y ===0 )
                snap_Y = 1;
            var snap = { X : snap_X, Y: snap_Y};
            return snap;
        }

        function setUndoValues()
        {
            $(".dashboard-container .dashboard-wrapper")
                .each(function (index, value) {
                    $('#undo_' + $(value).attr('id') + '_Position').val(index);
                    $('#undo_' + $(value).attr('id') + '_Height').val(value.style.getPropertyValue('--dashboard-height'));
                    $('#undo_' + $(value).attr('id') + '_Width').val(value.style.getPropertyValue('--dashboard-width'));
                });
        }

        function getCurrentValues()
        {
            var metadata = [];
            $(".dashboard-container .dashboard-wrapper")
                .each(function (index, value) {
                    var position = index;
                    var height = $(this)[0].style.getPropertyValue('--dashboard-height');
                    var width = $(this)[0].style.getPropertyValue('--dashboard-width');
                    var contentItemId = $(this).attr("id");

                    metadata.push( {
                        "ContentItemId" : contentItemId,
                        "Position" : position,
                        "Width" : width,
                        "Height": height
                    });
                });
            return metadata;
        }

        function calculateCellSize()
        {
            var container = document.getElementById("container");
            var styles = window.getComputedStyle(container);

            var rows = styles.getPropertyValue('grid-template-rows');
            var columns = styles.getPropertyValue('grid-template-columns');

            var rowGap = styles.getPropertyValue('grid-row-gap').replace('px','');;
            var columnGap = styles.getPropertyValue('grid-column-gap').replace('px','');;
            var height = rows.split(' ')[0].replace('px','');
            var width = columns.split(' ')[0].replace('px','');

            cellSize = {
                width: width,
                height: height,
                gap : {
                    width : columnGap,
                    height : rowGap
                }
            };
        }

        var _sortable = $(".dashboard-container").sortable({
            tolerance: "pointer",
            opacity: 0.7,
            handle: ".dashboard-handle",
            placeholder: {
                element: function(currentItem) {
                    return $('<div  class="dashboard-dragdrop-placeholder"><div></div></div>')[0];
                },
                update: function (container, p) {
                    return;
                }
            },
            start: function (e, ui) {

                if(_menu != null){
                    $(document).trigger('click');
                }

                setUndoValues();

                var dahsboard = ui.item[0];
                ui.placeholder[0].style.setProperty("--dashboard-width", dahsboard.style.getPropertyValue("--dashboard-width"));
                ui.placeholder[0].style.setProperty("--dashboard-height", dahsboard.style.getPropertyValue("--dashboard-height"));

            },
            update: function (event, ui) {
                var op = $('#undo_' + ui.item.attr('id') + '_Position');
                // Only update if Position is changed
                if(op.val() != ui.item.index()){
                    var changed =  getCurrentValues();
                    Update(changed);
                }
            }
        });
        $(".dashboard-wrapper").resizable({
            handles: "s,e,se",
            helper: "ui-resizable-helper"
,
            start: function (event, ui) {
                if(_menu != null){
                    $(document).trigger('click');
                }
                setUndoValues();
            },
            resize: function (event, ui) {

                var original = {
                    width : ui.originalSize.width,
                    height: ui.originalSize.height
                };

                var updated = {
                    width : ui.size.width,
                    height: ui.size.height
                };

                var snap = snapTo(original, updated, cellSize);

                ui.helper[0].style.setProperty("--dashboard-width", snap.X);
                ui.helper[0].style.setProperty("--dashboard-height", snap.Y);

                ui.helper.css("width", (snap.X * cellSize.width) + ((snap.X -1 ) * cellSize.gap.width)  );
                ui.helper.css("height", (snap.Y * cellSize.height) + ((snap.Y -1 ) * cellSize.gap.height) );
            },
            stop: function (event, ui) {

                $(this).css("width", '');
                $(this).css("height", '');

                var original = {
                    width : ui.originalSize.width,
                    height: ui.originalSize.height
                };

                var updated = {
                    width : ui.size.width,
                    height: ui.size.height
                };

                var snap = snapTo(original, updated, cellSize);

                var ow = $('#undo_' + ui.element.attr('id') + '_Width');
                var oh = $('#undo_' + ui.element.attr('id') + '_Height');

                // Only update if values have changed
                if(ow != snap.X || oh != snap.Y)
                {
                    ui.element[0].style.setProperty("--dashboard-width", snap.X);
                    ui.element[0].style.setProperty("--dashboard-height", snap.Y);

                    var changed =  getCurrentValues();
                    Update(changed);
                }
            }
        });

        $(window).on('show.bs.dropdown', function (e) {
            _menu = $(e.target).find('.dropdown-menu');
            $('body').append(_menu.detach());
            var eOffset = $(e.target).offset();
            _menu.css({
                'display': 'block',
                    'top': eOffset.top + $(e.target).outerHeight(),
                    'left': eOffset.left
            });
        });

        $(window).on('resize', function (e) {
            calculateCellSize();
        });

        $(window).on('hide.bs.dropdown', function (e) {
            $(e.target).append(_menu.detach());
            _menu.hide();
            _menu = null;
        });
    });
</script>