2011-06-21 30 views
1

我有這樣的麻煩。我想在AJAX請求後將JSON對象從Controller返回給View。 JS代碼:將JSON對象傳遞到MVC中的視圖3

 $.ajax(
     { 
       url : '/Order/GetArticleForBasicPosition', 
       data : article, 
       type : 'POST', 

       success : function (data) 
       { 
        alert("yyyyyyy");  
       }, 
       error:function (xhr, ajaxOptions, thrownError) 
       {     
         alert(xhr.status); 
         alert(thrownError); 
       } 
     }); 

器和控制器:

[HttpPost] 
    public JsonResult GetArticleForBasicPosition(string article) 
    { 
     Article articleInfo = _service.GetArticleForBasicPosition(article); 

     return Json(articleInfo); 
    } 

我也得到500內部服務器錯誤。我正在調試控制器,我發現它得到正確的參數「文章」和服務方法返回正確的對象。我嘗試了GET和POST類型的請求。

其實,當我修改我的控制器:

[HttpPost] 
    public JsonResult GetArticleForBasicPosition(string article) 
    { 
     var articleInfo = new Article() {GoodsName = "ffff", GoodsPrice = 1234, CatalogueName = "uuuuuuui"}; 

     return Json(articleInfo); 
    } 

一切正常。

我建議,原因是我的對象大小(我使用EntityFramework和articleInfo有很多導航屬性),但沒有發現任何人寫了關於同樣的麻煩。

有沒有人知道這種麻煩的原因是什麼,如果是物體的大小,最好的解決方法是什麼?

謝謝。

回答

3

我建議原因是我的對象大小(我使用EntityFramework和articleInfo有很多導航屬性),但沒有找到任何人寫過關於同樣的麻煩。

Ayende wrote blogged it。本網站上的許多of my answers在asp.net-mvc標籤中大約是it

it被稱爲視圖模型。你絕不應該將任何域對象傳遞給你的視圖。您應該設計專門針對視圖需求並僅包含必要屬性的視圖模型。

我想這個問題來自於一個事實,即無論是你的域模型包含這顯然不能被序列化到JSON或正在執行結果的時刻,串行試圖觸摸你通過模型的一些遞歸結構,你的數據上下文早已消失並被處置。

那麼試試這個:

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

還要確保_service.GetArticleForBasicPosition不拋出一個異常,你可能會得到一個500錯誤。

+0

可以üPLZ看看http://stackoverflow.com/questions/6410756/using-different-overload-of-datacontext-in-linq-to-sql –

+0

+1解釋關於傳遞域的缺陷對象的意見。 –

相關問題