gpt4 book ai didi

javascript - 将数据从 javascript 传递到 MVC Controller

转载 作者:行者123 更新时间:2023-12-02 16:03:50 25 4
gpt4 key购买 nike

我有一个使用 Vis.js 库构建的树层次结构。我的项目是asp.net MVC。

树中的每个节点都有一个 id。要求是,当我单击任何节点时,应将 id 传递给 Controller ​​,并渲染与调用的 Controller 操作方法对应的 View 。

我有一个显示树的 View ,如下所示: enter image description here

当我单击树中的任何节点(例如 105)时,我希望将节点 ID 传递给 Controller ​​操作方法“Tree1”。 Tree1 方法将进行一些计算并呈现其自己的 View 。

[HttpPost]
public ActionResult Tree1(string a)
{
return View();
}

为了将 id 从 TreeView 传递到 Tree1 Controller 操作方法,我使用 $.ajax()。这是我在网上的各个论坛上找到的。

network.on('selectNode',function(properties)
{
$.post({url: '@Url.Action("Tree1")',a:properties.nodes.toString()});
@*$.ajax({
url: '@Url.Action("Tree1")',
type: 'POST',
data: {a:properties.nodes.toString()},
success: function(result) {
//process the results from the controller
}
});*@
}
);

现在,这确实将数据发送到方法 Tree1(我在调试时可以看到),但 Tree1 的 View 未渲染。相反,渲染前一个 View 本身,显示树。

我想将数据从 javascript 传递到 Controller 操作方法,这样就不会将响应发送回调用的 javascript 代码。网上的所有 Material 都建议将响应发送回调用 JavaScript 的解决方案。

你能帮我解决这个问题吗?我是否缺少任何基本概念?如何将数据从 javascript 传递到 Controller 方法,而被调用的方法不必将任何响应发送回调用 javascript?

更新1

<script type="text/javascript">
// create an array with nodes
var nodes = new vis.DataSet([]);

@foreach(DataRow @dr in Model.Tree.Tables[0].Rows)
{
@:nodes.add({id: @dr[0], label:@dr[0].ToString(), level:@dr[3]});
}

var edges = new vis.DataSet([]);
@foreach(DataRow @dr in Model.Tree.Tables[0].Rows)
{
if(@dr[2].ToString()!="")
{
@:edges.add({from:@dr[2], to:@dr[0]});
}
}

// create a network
var container = document.getElementById('mynetwork');

// provide the data in the vis format
var data = {
nodes: nodes,
edges: edges
};
var options = {nodes:{shape:'ellipse'},edges:{arrows: 'to'},physics:true};

// initialize your network!
var network = new vis.Network(container, data, options);

network.on('selectNode',function(properties)
{

$.ajax({
url: '@Url.Action("Tree1")',
type: 'POST',
data: {a:properties.nodes.toString()},
success: function(result) {
//process the results from the controller
}
});
}
);


</script>

最佳答案

由于您只想导航到 View ,因此可以使用以下命令:

network.on('selectNode',function(properties)
{
var url = '@Url.Action("Tree1")' + '?a=' +properties.nodes.toString();
document.location = url;
});

关于javascript - 将数据从 javascript 传递到 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com