在ASP.NET MVC 4中調用JSON文件

[英]Calling to JSON file in ASP.NET MVC 4


I started to learn ASP.NET MVC 4, did some small stuff...

我開始學習ASP.NET MVC 4,做了一些小事......

In my index page I want to get JSON file with some data and display it on the main page.

在我的索引頁面中,我想獲取包含一些數據的JSON文件並將其顯示在主頁面上。

In simple HTML,JavaScript I using ajax to GET/POST JSON data

在簡單的HTML中,JavaScript我使用ajax來獲取GET / POST JSON數據

<script>
$.ajax({
     type : "GET",
     dataType : "json",
     url : "www.site.com",
     success: function(data){
           alert(data);
     }
});
</script>

I created MVC 4 project, where should I call the jQuery $.ajax command to get data and display it ?

我創建了MVC 4項目,我應該在哪里調用jQuery $ .ajax命令來獲取數據並顯示它?

Do I have to call it in the View? and with the jQuery syntax?

我必須在視圖中調用它嗎?和jQuery語法?

I'll be happy to see any example

我很樂意看到任何一個例子

4 个解决方案

#1


13  

You could put this in a separate javascript file that could be referenced from your view. For example:

您可以將它放在一個單獨的javascript文件中,該文件可以從您的視圖中引用。例如:

<script type="text/javascript" src="~/scripts/myscript.js"></script>

and inside the script make the AJAX call:

在腳本內部進行AJAX調用:

$.ajax({
    type : "GET",
    dataType : "json",
    url : "/SomeController/SomeAction",
    success: function(data) {
        alert(data);
    }
});

The controller action you are invoking should obviously return a JsonResult:

您正在調用的控制器操作顯然應該返回一個JsonResult:

public ActionResult SomeAction()
{
    var model = new
    {
        Foo = "Bar",
    }
    return Json(model, JsonRequestBehavior.AllowGet);
}

There's a further improvement to be made to this javascript. You may notice the hardcoded url to the controller action:

這個javascript還有待進一步改進。您可能會注意到控制器操作的硬編碼URL:

url : "/SomeController/SomeAction",

This is not good because the pattern of your urls is governed by routes and if those routes change you will also have to modify your javascript. Also if you deploy your application inside a virtual directory in IIS, this path no longer will take into account the virtual directory name.

這不好,因為你的網址模式由路由管理,如果這些路由發生變化,你還需要修改你的javascript。此外,如果將應用程序部署在IIS中的虛擬目錄中,則此路徑不再考慮虛擬目錄名稱。

For this reason it is always recommended to use url helpers to generate the url to a controller action. For example you could store this into a global javascript variable in the view:

因此,始終建議使用url helper生成控制器操作的url。例如,您可以將其存儲到視圖中的全局javascript變量中:

<script type="text/javascript">
    var myActionUrl = '@Url.Action("SomeAction", "SomeController")';
</script>
<script type="text/javascript" src="~/scripts/myscript.js"></script>

and then in your javascript file use this variable:

然后在你的javascript文件中使用這個變量:

$.ajax({
    type : "GET",
    dataType : "json",
    url : myActionUrl,
    success: function(data) {
        alert(data);
    }
});

#2


2  

Try the following

請嘗試以下方法

Controller

調節器

public class JsonController : Controller
{
    public ActionResult Simple()
    {
        return View();
    }

    public JsonResult SimpleJson()
    {
        var persons = new List<Person>
        {
            new Person{Id=1, FirstName="Harry", LastName="Potter"},
            new Person{Id=1, FirstName="James", LastName="Potter"}
        };

        return Json(persons, JsonRequestBehavior.AllowGet);
    }
}

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

In simple.aspx view

在simple.aspx視圖中

<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Simple</title>
    <script src="../../Scripts/jquery-2.0.3.intellisense.js"></script>
    <script src="../../Scripts/jquery-2.0.3.js"></script>
    <script src="../../Scripts/jquery-2.0.3.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#FillButton').click(function () {
                $.getJSON("/Json/SimpleJson", null, function (data) {
                    var div = $('#ajaxDiv');
                    $.each(data, function (i, item) {
                        div.append("<br /><br />First Name: " + item.FirstName);
                        div.append("<br />Last Name: " + item.LastName);
                    });
                });
            });
        });
    </script>


    <div>
          <div id="ajaxDiv">
        </div>
       <input id="FillButton" type="button" value="Get Persons" />        
    </div>

#3


1  

You have to make ajax call in view, just call MVC url which return json data and operate on that data.

你必須在視圖中進行ajax調用,只需調用返回json數據的MVC url並對該數據進行操作。

<script>
$.ajax({
 type : "GET",
 dataType : "json",
 url : "www.site.com/{controller}/{action}/{id}",
 success: function(data){
       alert(data);
 }
});
</script>

pass the Controller, Action and Id part whichever is applicable in the ajax call. Hope this will help you

傳遞Controller,Action和Id部分,適用於ajax調用。希望對你有幫助

#4


1  

You can call ajax function from your view, like below.

您可以在視圖中調用ajax函數,如下所示。

    var oModel = {};
    oModel.Id = $('#hiddenid').val();
    oModel.Name = $('#hiddenName').val();;  

      $.ajax({
            url: "/SomeController/SomeActionMethod",
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(oModel),
        }).done(function (data) {
            alert(JSON.stringify(data));
        });

and have method named "SomeActionMethod" in your controller like below,

並在您的控制器中使用名為“SomeActionMethod”的方法,如下所示,

    [HttpGet]
    public ActionResult SomeActionMethod(oModel oVarModel)
    {
         //Do some stuff

        return someReturn;
    }

Hope this helps.

希望這可以幫助。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/12/31/e722273d3a1f2393474e9709d7bcac11.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com