简体   繁体   中英

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. 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" 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:

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.

Another possibility is to retrieve the data directly from javascript with an ajax request. This example uses jQuery's $.ajax function:

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
         }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM