How to get Data from Model to JavaScript MVC 4?

后端 未结 4 1946
借酒劲吻你
借酒劲吻你 2021-02-13 23:10

that\'s my function:

 

        
4条回答
  •  长情又很酷
    2021-02-13 23:33

    You need to create actions (methods in the controller) that return JsonResult.

    From the client side, make ajax calls to the server to recover and use that data. The easiest way to do this is to use any of the jQuery ajax methods.

       public JsonResult GetData(int id)
        {
            // This returned data is a sample. You should get it using some logic
            // This can be an object or an anonymous object like this:
            var returnedData = new
            {
                id,
                age = 23,
                name = "John Smith"
            };
            return Json(returnedData, JsonRequestBehavior.AllowGet);
        }
    

    When you use a jQuery get to the /ControllerName/GetData/id, you'll get a JavaScript object in the success callback that can be used in the browser. This JavaScript object will have exactly the same properties that you defined in the server side.

    For example:

    function getAjaxData(id) {
        var data = { id: id };
        $.get('/Extras/GetData/1', // url
            data, // parameters for action
            function (response) { // success callback
                // response has the same properties as the server returnedObject
                alert(JSON.stringify(response)); 
            },
            'json' // dataType
        );
    }
    

    Of course, in the success callback, instead of making an alert, just use the response object, for example

    if (response.age < 18) { ... };
    

    Note that the age property defined in the server can be used in the JavaScript response.

提交回复
热议问题