0

I confess, its a very basic question. But I am actually fed up with it. I am just trying to send my current time in JSON format from my action method to the view. In the view code, I am trying to fetch the result using jQuery ajax() method. But while in the success attribute, I am unable to fetch the result from the response. Tried numerous ways like response.d etc. But ended up with nothing almost.

Here goes the relevant code snippets:

Action method:

 public JsonResult GetDateTest()
        {
            return Json(DateTime.Now.ToString(), JsonRequestBehavior.AllowGet);
        }

script in the view:

<script type="text/javascript">

    $(document).ready(function () {

        $("#Button1").click(function (e) {

            $.ajax({


                type: 'POST',

                url: '@Url.Action("GetDateTest","GetDate")',

                data: '{}',

                contentType: 'application/json; charset=utf-8',

                dataType: 'json',

                success: function (response) {

                    //how can I read the date here and display it on the standard //controls like a label?

                },

                error: function (e) {
                    alert("error");
                }

            });

        });

    });
</script>

Help me to figure it out with proper explanation

1
  • 1
    Use your browser's developer tools to find out what the response object looks like, then you'll know what property to access in it. Commented Feb 13, 2013 at 9:08

2 Answers 2

1

if you want to get data as json, modify your controller action:

public JsonResult GetDateTest()
{
    return Json(new { date = DateTime.Now.ToString() }, JsonRequestBehavior.AllowGet);
}

add success function:

success: function (response) {
    $("#someLabel").html(response.date);
},

html

<div id="someLabel"></div>
Sign up to request clarification or add additional context in comments.

4 Comments

How can I get an object's property like this ? say I have an employee class like this: public class Employee { public int Id { get; set; } public string Name { get; set; } public decimal Salary { get; set; } }...How can I retrieve the id,Name or salary value inside the ajax() method ?
if use return Json(employee, JsonRequestBehavior.AllowGet); Json will convert your class to Json data.
I need one more help from you..Suppose I have a form..I want to submit all its Text Boxs' data in a single ajax post..How can I achieve this ?
1

From jQuery.ajax()

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
...
"json": Evaluates the response as JSON and returns a JavaScript object.

So, in your case the response should be already parsed as JSON and returned as a javascript string.

Since you don't pass any data, you can just use the default method of GET and reduce your example to

$.ajax({
    url: '@Url.Action("GetDateTest","GetDate")',
    dataType: 'json',
    success: function (response) {
        console.log(response);
    },
    error: function (e) {
        alert("error");
    }
});

If you don't need an error callback, you can use jQuery.getJSON() instead and simplify it further

$.getJSON('@Url.Action("GetDateTest","GetDate")',
          function (response) {
              console.log(response);
          });

Update to comment:

To access an object's properties, you must encode it as a JSON object

{
    "id": 423,
    "name": "john doe",
    "salary": 50000
}

and in the ajax success function, you can access it as the response's properties

success: function(data) {
    var id = data.id;
    var name = data.name;
    var salary = data.salary;
    // do something with data properties
}

1 Comment

@Md.ArafatAlMahmud You must encode it as a JSON object, see updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.