开发者

asp.net mvc and json

开发者 https://www.devze.com 2023-03-28 00:26 出处:网络
I have the follow开发者_如何学JAVAing class: [DataContract] public class FileUploaderResult { [DataMember]

I have the follow开发者_如何学JAVAing 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消