开发者

Javascript Deserialize is returning the class name instead of actual object

So I'm running GetServerUpdateProgress() in the controller from a $.ajax call on my page. While debugging I can confirm that the variable: myobj is being properly created and filled with the correct data.

But when on the $.ajax success, I'm not getting the data in json format, instead I'm getting a string of "TrackerMVC.ClassLib.UpdateAJAXProgress" - the objects type.

I've done this in the past with a .svc webservice and didn't have any problems getting the object values using this exact same method.

Any ideas? Thanks!

method:

public UpdateAJAXProgress GetServerUpdateProgress()
{
        string BASE_URL = "http://localhost:55094";
        string url = BASE_URL + "/Home/UpdateProgress";
        WebRequest wr = WebRequest.Create(url);
        wr.Credentials = CredentialCache.DefaultNetworkCredentials; // uses current windows user

        var myojb = new UpdateAJAXProgress();
        var response = (HttpWebResponse)wr.GetResponse();
        var reader = new开发者_运维百科 StreamReader(response.GetResponseStream());
        JavaScriptSerializer js = new JavaScriptSerializer();
        var objText = reader.ReadToEnd();
        myojb = (UpdateAJAXProgress)js.Deserialize(objText, typeof(UpdateAJAXProgress));
        return myojb; // during debugging this object has the correct values in the correct format
}

class:

public class UpdateAJAXProgress
{
    public int Completed { get; set; }
    public int Total { get; set; }
}

javascript:

$.ajax({
        type: "POST",
        async: false,
        url: '@(Url.Action("GetServerUpdateProgress","Charts"))',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data); // data being returned is: "TrackerMVC.ClassLib.UpdateAJAXProgress"
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.status);
            alert(XMLHttpRequest.responseText);
        }
});


You're misusing MVC.

You should declare your function as returning ActionResult, then return Json(myobj).

If you return a non-ActionResult from an MVC action, MVC will convert it to a string by calling ToString().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜