Oleg Sh
Oleg Sh

Reputation: 9013

asp.net mvc and json

I have the following class:

[DataContract]
public class FileUploaderResult
{
    [DataMember]
    public bool Success { get; set; }
    [DataMember]
    public string TempFileName { get; set; }

    public FileUploaderResult(bool success, string fileName, string errorMessage)
    {
        this.Success = success;
        //this.RelativeThumbnailUrl = fileName;
        //this.ErrorMessage = errorMessage;
    }
}

and following controller method:

    public JsonResult UploadFileAjax()
    {
        var result = new FileUploaderResult(false, string.Empty, string.Empty);
        try
        {
            //...
            result.Success = true;
            result.TempFileName = filename;
            return Json(result);
        }
        catch
        {
            result.Success = false;
            return Json(result);
        }
    }

on client part I try to parse this JSON :

                var objResponse = jQuery.parseJSON(response);
                alert(objResponse.TempFileName);

and it does not work. When I try to show response as is:

                alert(response);

I got the message with "litter" (

http://ru.magicscreenshot.com/jpg/e8f4D1ciAU8.html

why parseJSON does not work and how to do correctly?

Upvotes: 0

Views: 181

Answers (1)

Guffa
Guffa

Reputation: 700152

That is because you are requesting the data as HTML, not plain text or JSON. The browsers wraps the text in the response in a pre tag to make an HTML page out of it.

When you request the data, specify the data type "json", then the browser will not try to make HTML out of it, and jQuery will parse it for you and return an object.

Upvotes: 4

Related Questions