2017-02-21 36 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