ASP.Net MVC 将数据从脚本传递到新视图

ASP.Net MVC passing data from script to new view

大家好,感谢您首先阅读此消息。

我目前正在努力处理 ASP.Net MVC 框架项目,以便在视图之间传递数据。

我有一个带有索引视图的控制器模型和一个 javascript,它可以帮助我获取在 canvas 中呈现的 3d 模型上单击的对象的 ID。这是视图:

<div class="col-md-10">
    <canvas id="viewer"></canvas>
</div>
<div class="col-md-2">
    <btn id="AddEventObjects" class="btn btn-eiffage-red">Create a task</btn>
    <table id="selectedElements" class="table table-striped">
        <thead><tr><th>Selected parts</th></tr></thead>
    </table>
</div>

<script type="text/javascript">
    var viewer = new xViewer('viewer');
    var selectedIds = [];
    viewer.on('loaded',
        () => {
            viewer.start();
        });

    viewer.on('pick', function (args) {
        if (args == null || args.id == null) {
            return;
        }        
        var id = args.id;

        //If the id was previously clicked then remove it from the list and remove the highlight
        if (selectedIds.includes(id)) {
            var index = selectedIds.indexOf(id);
            selectedIds.splice(index, 1);            
        } else {            
            selectedIds.push(id);            
        }


        //Add elements to the table
        var table = document.getElementById('selectedElements');
        var oldtbody = document.getElementById('selectedElementsBody');
        if (oldtbody) {
            oldtbody.remove();
        }
        var tbody = document.createElement('tbody');
        tbody.id = "selectedElementsBody";
        for (var i = 0; i < selectedIds.length; i++) {
            var row = document.createElement('tr');
            var cell = document.createElement('td');
            cell.textContent = selectedProperties[i];
            row.appendChild(cell);
            tbody.appendChild(row);
            table.appendChild(tbody);
        }
    });
    viewer.load('../Content/3d/Maintenance.wexbim');
</script>

使用下面的脚本我想打开另一个 window 传递 selectedIds 数组:

<script type="text/javascript">
        $('#AddEventObjects').click(function () {
            $.ajax({
                url: "@(Url.Action("AddEventObjects", "Planning"))",
                type: "GET",
                dataType : "json",
                data: { selectedObjects: selectedIds},
                cache: false,
                async: true,
                traditional: true,
                success: function (data) {
                    window.location = "/Planning/AddEventObjects";
                },
                error: function () {
                    alert("error");
                }
            });
        });
</script>

知道我的控制器 Planning 有一个名为 AddEventObjects 的操作:

public ActionResult AddEventObjects(string[] selectedObjects) {
            ViewBag.Title = "Ajout intervention";
            var addEventObjectsViewModel = new AddEventObjectsViewModel {
                Title = "",
                StartTime = "",
                EndTime = "",
                AllUsers = _context.Users.ToList(),
                SelectedUsers = new List<ApplicationUser>(),
                PostedUsers = new PostedUsers(),
                ObjectsIds = selectedObjects.ToList(),
            };
            addEventObjectsViewModel.PostedUsers.SelectedIds = addEventObjectsViewModel.SelectedUsers.Select(x => x.Id).ToArray();
            return View(addEventObjectsViewModel);
}

我希望它打开以下显示 selectedIds 的视图:

@model Maintenance.Web.Models.AddEventObjectsViewModel

using (Html.BeginForm("AddEvent", "Planning", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) {
        @Html.AntiForgeryToken()
        <h4>Créer une nouvelle intervention</h4>

        <div class="form-horizontal col-md-12">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-row col-md-12">
                <div class="col-md-4">
                    <div class="form-group">
                        @Html.LabelFor(m => m.ObjectsIds, htmlAttributes: new { @class = "control-label" })
                        <table class="table table-striped" style="width:100%; margin-top:20px">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                </tr>
                            </thead>
                            @if (Model != null) {
                                foreach (var objectId in Model.ObjectsIds) {
                                    <tr>
                                        <td>@objectId</td>
                                    </tr>
                                }
                            }
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <div class="col-md-10">
                        <input type="submit" class="btn btn-eiffage-red" value="Ajouter" />
                    </div>
                </div>
            </div>
    }

有一个更基本的问题:如何将数组从视图中的 javascript 传递到另一个视图?

非常感谢您的帮助。

如果要传递数据数组,有几种方法。最简单的方法是执行以下操作。将数组 IDS 连接成逗号分隔的字符串:

var idList = data.PostedUsers.SelectedIds.join(); //comma sep list
window.location = "/Planning/AddEventObjects?ids=" + idList;

这将非常简单地与您所拥有的一起工作;它将构建一个 URL 像:

/Planning/AddEventObjects?ids=1,2,3,4

在后台,你有一个“string ids”参数,用逗号分隔,然后根据需要使用 ID。

谢谢 Brian Mains!

我按照您的建议在 url 中传递了数据。 我只是使用 Json 序列化数据而不是逗号分隔值:

<a id="CreateEvent" class="btn" href="">Créer une intervention</a>

...

var createLink = "/Planning/AddEventObjects?ids=" + JSON.stringify(model.ids);
$('#CreateEvent').attr("href", createLink);

然后在我的控制器中:

    public ActionResult AddEventObjects(string ids) {
        if (ids == null) {
            return HttpNotFound();
        }

        string[] objectIds = JsonConvert.DeserializeObject<string[]>(ids);
    }