Calling to JSON file in ASP.NET MVC 4

后端 未结 4 1170
半阙折子戏
半阙折子戏 2021-01-02 21:44

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

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

相关标签:
4条回答
  • 2021-01-02 22:26

    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

    <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>
    
    0 讨论(0)
  • 2021-01-02 22:27

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

        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,

        [HttpGet]
        public ActionResult SomeActionMethod(oModel oVarModel)
        {
             //Do some stuff
    
            return someReturn;
        }
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-02 22:29

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

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

    and inside the script make the AJAX call:

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

    The controller action you are invoking should obviously return a 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:

    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.

    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:

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

    $.ajax({
        type : "GET",
        dataType : "json",
        url : myActionUrl,
        success: function(data) {
            alert(data);
        }
    });
    
    0 讨论(0)
  • 2021-01-02 22:36

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

    <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

    0 讨论(0)
提交回复
热议问题