[英]Using ajax post to transfer data from JS to a function in Controller in asp.net mvc. But the view is not changed
[英]Transfer Data from ASP:NET MVC Controller to view
我在控制器中有一个对象,我想在视图和JavaScript代码中使用它们,但使用ViewBag无法实现。 我的代码听到:
public class MyController : Controller
{
public async Task<ActionResult> Index()
{
using (var client = new HttpClient())
{
string response = await client.GetStringAsync("http://api/controller/....");
ViewBag.VB = response;
return View();
}
}
}
和我的看法:
@{
ViewBag.Title = "Index";
}
@section Javacript
{
<script type="text/javascript">
function MyFunction() {
**** //I want to use DATA hear. *********
};
</script>
}
<div id="info">
</div>
我怎样才能做到这一点? 有人有主意吗?
您可以将数据放入<script type="text/html">
节点,然后通过document.getElementById
从javascript访问数据
<script type="text/html" id="data">@ViewBag.VB</script>
<script>
function MyFunction() {
var data = document.getElementById('data').innerHTML;
// if the data is in the json format, you can use JSON.parse:
data = JSON.parse(data);
// TODO: do something with data
}
</script>
您也可以将数据直接插入javascript:
function MyFunction() {
var data = '@(ViewBag.VB)'; // or omit the single quotes if it's json data
// TODO: do something with data
}
此方法要求将javascript代码嵌入到.cshtml
文件中。
另一种可能性是使用ajax请求直接从javascript中检索数据。 此示例使用jQuery的$ .ajax函数:
function MyFunction() {
$.ajax({
url: "/api/controller/...",
contentType: "application/json", // tell the api-controller that we want json
dataType: "application/json", // tell the jQuery callback that it is json
success: function (data) {
// TODO: do something with data
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.