1

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"}}
asked Feb 29, 2012 at 12:20
2
  • I have tried to parse with $.parseJSON(e.response) but it do not work. Commented Feb 29, 2012 at 12:24
  • What did it do or not do? Were there any errors? Commented Feb 29, 2012 at 12:26

2 Answers 2

3

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);
senfo
29.1k16 gold badges79 silver badges106 bronze badges
answered Feb 29, 2012 at 12:25
Sign up to request clarification or add additional context in comments.

1 Comment

That was my problem! I was trying to over parse my response. I just needed to call the property! Thanks!
0

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.

answered Feb 29, 2012 at 12:24

1 Comment

Any idea what was undefined? The function? Are you using something like Firebug or the Developers Tools in Chrome to help you out?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.