2017-02-21 84 views
0

我想通過ajax調用填充下拉列表我的代碼工作正常,直到我發回JSON格式的結果(對象列表)。用json和實體框架填充下拉列表

這是我試圖填補我的實體模型:

public partial class stkInvoicesTypesTbl 
{ 
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] 
    public stkInvoicesTypesTbl() 
    { 
     this.stkInvoicesTbls = new HashSet<stkInvoicesTbl>(); 
    } 

    public int invTypesTableId { get; set; } 
    public string invTypeDesc { get; set; } 

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] 
    public virtual ICollection<stkInvoicesTbl> stkInvoicesTbls { get; set; } //this property throw Exception and i think here is my problem 
} 

這裏是我的ajax調用和腳本代碼

var InvType = [] 

// fetch invoice type from database 
function LoadInvoiceType(element) 
{ 
    if (InvType.length == 0) { 
     //ajax function to fetch data 
     $.ajax({ 
      type: "GET", 
      url: '/InvoiceItm/getInvoiceType', 

      success: function (data) { 
       InvType = data; 

       renderInvoiceType(element); 
      }, 
      error: function (data) { 
       InvType = data; 
      } 
     }) 
    } 
    else { 
     //render invoice type to elements 
     renderInvoiceType(element); 
    } 
} 

function renderInvoiceType(element) 
{ 
    var $ele = $(element); 
    $ele.empty(); 

    $.each(InvType, function (i, val) { 
     $ele.append($('<option/>').val(val.invTypesTableId).text(val.invTypeDesc)); 
    }) 
} 

我的動作控制器:

public JsonResult getInvoiceType() 
{ 
     List<stkInvoicesTypesTbl> InvoiceTypes = new List<stkInvoicesTypesTbl>(); 

     using (iraqEntities dc = new iraqEntities()) 
     { 
      InvoiceTypes = dc.stkInvoicesTypesTbls.OrderBy(a => a.invTypeDesc).ToList(); 
     } 

     return new JsonResult { Data = InvoiceTypes, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; 
} 

我查看:

<td><label for="input-text" class="col-sm-1 control-label">Invoice Type</label> </td> 
      <td> 
       <select type="text" id="InvoiceType" class="col-sm-3 form-control" onchange="LoadInvoiceType(this)"></select> 

      </td> 

我的列表在控制器中正確填寫,但是當我以json格式發回(返回JsonResult ...)時,它返回錯誤。

這裏是一些截圖爲我調試可能會有所幫助:

return my data from database and fill my list in controller

this property is generated automatically from Entity Framework (foreign key relation) and it's throwing an exception so I think my problem lies here

所以,任何人都可以幫助我在我的問題是可以理解的

+0

嗨我想你需要使用包括在你的查詢。 –

+0

是的,現在的工作,謝謝親愛的。 – Moro

+0

歡迎我希望我把它作爲答案:) –

回答

0

你需要在查詢中包含屬性stkInvoicesTbls

using (iraqEntities dc = new iraqEntities()) 
    { 
     InvoiceTypes = dc.stkInvoicesTypesTbls 
         .Include("stkInvoicesTbls") 
         .OrderBy(a => a.invTypeDesc) 
         .ToList(); 
    } 
+0

我嘗試它,它給我的語法錯誤:不能將lambda表達式轉換爲類型'字符串',因爲它不是委託類型。 @Ahmed Ragheb – Moro

+0

@Moro我編輯答案 –

+0

現在的工作非常感謝@Ahmed Ragheb – Moro