Tomas
Tomas

Reputation: 18097

ASP.NET MVC 3 Parse JSon object and display data

I have a class

public class ConversionResultModel
    {
        public string ProcessId { get; set; }
        public bool Result { get; set; }
        public string Message { get; set; }         
    }

sending it to view using JSon

   public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> clientUpload)
    {
        string destinationPath = "";
        JsonResult result = null;
        var fileModel = new ConversionResultModel();
        fileModel.ProcessId = "4558-95559-554";
        fileModel.Result = true;
        fileModel.Message = "test.pdf";
        result = Json(new { fileModel }, "text/plain");


        return result;
    }

How to parse such JSon object at client side using JS or jQuery and read values?

I have tried to parse JSon object with code below but get Undefined error in alert

 var obj = $.parseJSON(e.response);
 alert(e.obj);

I receive JSon object like this

{"fileModel":{"ProcessId":"4558-95559-554","Result":true,"Message":null,"SourceFile":null,"ConvertedFileName":"test.pdf","ConvertedFileSize":1233444,"DownloadUrl":"http://localhost:2008/download?path=4558-95559-554","DeleteUrl":"http://localhost:2008/download?path=4558-95559-554"}}

Upvotes: 1

Views: 5493

Answers (2)

senfo
senfo

Reputation: 29026

http://api.jquery.com/jQuery.parseJSON/

In your case, I think you're getting back the correct JSON, but your alert is looking at the wrong object. Try alert(obj.SomeProperty) rather than alert(e.obj). e.obj doesn't exist, which is likely why you're getting an "undefined" error. For example, alert(obj.fileModel.ProcessId); should work.

Upvotes: 0

Samich
Samich

Reputation: 30095

You do not need to parse it. Just set data type to JSON during ajax request and then use received data object like entity and you easily can access to any property:

var id = data.ProcessId;

Anyway, using jQuery you can parse JSON string:

var data = jQuery.parseJSON(stringData);

P.S:

Use the following code sample for converting object to JSON in ASP.NET MVC:

return this.Json(fileModel);

Upvotes: 3

Related Questions