![](/img/trans.png)
[英]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.