从ASP:NET MVC Controller传输数据以查看

时间:2014-09-27 20:44:35

标签: javascript c# asp.net asp.net-mvc asp.net-mvc-4

我在控制器中有一个对象,我想在视图和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>

我该怎么做?有人有想法吗?

1 个答案:

答案 0 :(得分:1)

您可以将数据放入<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&#39; $.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
         }
    });
}