[英]Transfer Data from ASP:NET MVC Controller to view
I have an object in contrroller and I want to use them in view and in javascript code but I can't achived using ViewBag. 我在控制器中有一个对象,我想在视图和JavaScript代码中使用它们,但使用ViewBag无法实现。 my code hear :
我的代码听到:
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();
}
}
}
and my view : 和我的看法:
@{
ViewBag.Title = "Index";
}
@section Javacript
{
<script type="text/javascript">
function MyFunction() {
**** //I want to use DATA hear. *********
};
</script>
}
<div id="info">
</div>
How can I do this? 我怎样才能做到这一点? Anyone have an idea?
有人有主意吗?
You can put your data into a <script type="text/html">
node and access it from javascript via document.getElementById
您可以将数据放入
<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>
You can also insert the data directly into javascript: 您也可以将数据直接插入javascript:
function MyFunction() {
var data = '@(ViewBag.VB)'; // or omit the single quotes if it's json data
// TODO: do something with data
}
This approach requires that the javascript code is embedded into the .cshtml
file. 此方法要求将javascript代码嵌入到
.cshtml
文件中。
Another possibility is to retrieve the data directly from javascript with an ajax request. 另一种可能性是使用ajax请求直接从javascript中检索数据。 This example uses jQuery's $.ajax function:
此示例使用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.