当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Transfer of JSON objects to View in MVC 3

问题描述:

I have such a trouble. I want to return JSON object from Controller to View after AJAX request.

JS code is:

 $.ajax(

{

url : '/Order/GetArticleForBasicPosition',

data : article,

type : 'POST',

success : function (data)

{

alert("yyyyyyy");

},

error:function (xhr, ajaxOptions, thrownError)

{

alert(xhr.status);

alert(thrownError);

}

});

And Controller is:

 [HttpPost]

public JsonResult GetArticleForBasicPosition(string article)

{

Article articleInfo = _service.GetArticleForBasicPosition(article);

return Json(articleInfo);

}

And I get 500 Internal Server Error. I was debugging controller and I see that it gets correct parameter 'article' and service methhod returns correct object. I tryed both GET and POST types of request.

Actually when I modified my controller as:

 [HttpPost]

public JsonResult GetArticleForBasicPosition(string article)

{

var articleInfo = new Article() {GoodsName = "ffff", GoodsPrice = 1234, CatalogueName = "uuuuuuui"};

return Json(articleInfo);

}

everything went ok.

I suggest that the reason is my object size(I use EntityFramework and articleInfo has a lot of navigation properties), but didn't found anybody who wrote about the same trouble.

Does anybody know what is the reason of such trouble and if it is size of the object what is the best practice to solve it?

Thanks.

网友答案:

I suggest that the reason is my object size(I use EntityFramework and articleInfo has a lot of navigation properties), but didn't found anybody who wrote about the same trouble.

Ayende wrote blogged it. Many of my answers on this site in the asp.net-mvc tag are about it.

The it is called view models. You should never pass any domain objects to your views. You should design view models specifically tailored to the needs of the view and containing only the necessary properties.

I guess the problem comes from the fact that either your domain models contain some recursive structure which obviously cannot be serialized into JSON or at the moment the result is being executed and the serializer tries to touch the model you passed, your data context is long gone and disposed.

So try this:

[HttpPost]
public JsonResult GetArticleForBasicPosition(string article)
{
    Article articleInfo = _service.GetArticleForBasicPosition(article);
    return Json(new
    {
        Property1NeededByTheView = x.Foo,
        Property2NeededByTheView = x.Bar.Baz
    });
}

Also ensure that _service.GetArticleForBasicPosition doesn't throw an exception or you might get a 500 error.

分享给朋友:
您可能感兴趣的文章:
随机阅读: