在序列化类型&System; System.Reflection.RuntimeModule'的对象时检测到循环引用。 MVC JSON

时间:2017-10-23 12:08:34

标签: javascript c# jquery json model-view-controller

我需要在Json的帮助下显示一个表,但是我收到了错误。

  

在序列化类型为' System.Reflection.RuntimeModule'

的对象时检测到循环引用

Index.cshtml

var table = $('#maintable').DataTable({
            "ajax": {
                "type": "POST",
                "url": '@Url.Action("BindDatatable", "Sales")',
                 "data": { itemtyyID: $("#ddl_item").val(), itloccid: $("#getlocation").val() },
                 //"contentType": application/json,
                "traditional": true,
                "datatype": "json",
                "dataSrc": function (json) {
                    //Make your callback here.
                    alert("Done!");
                   // var x = JSON.parse(json);
                   // return x;
                    return json.data;
                }
            },
            "columns": [
                    { "data": "Item", "autowidth": true },
                    { "data": "qty", "autowidth": true },
                    { "data": "rate", "autowidth": true },
                    { "data": "ppb", "autowidth": true, "visible": false }

            ],
            select: true
        });

SalesController.cs

 [HttpPost]
    public JsonResult BindDatatable(string itemtyyID, string itloccid)
    {

        Int32 itemtyyIDD, itloccIDD;

        DataSet ds = new DataSet();
        if (!string.IsNullOrEmpty(itemtyyID) && !string.IsNullOrEmpty(itloccid))
        {

            itemtyyIDD = Convert.ToInt32(itemtyyID);
            itloccIDD = Convert.ToInt32(itloccid);
        }
        else
        {

            itemtyyIDD = 0;
            itloccIDD = 0;
        }

        DataTable dt = new DataTable();
        OracleCommand cmdsp = new OracleCommand();
        cmdsp.CommandType = System.Data.CommandType.StoredProcedure;
        cmdsp.CommandText = "Pkg_Inventory.Prc_sale_stock";
        cmdsp.Parameters.Add("ITEMYYID", OracleType.Int32, 25).Value = itemtyyIDD;
        cmdsp.Parameters.Add("ITLOCID", OracleType.Int32, 25).Value = itloccIDD;
        cmdsp.Parameters.Add("SALESTOCK", OracleType.Cursor).Direction = ParameterDirection.Output;
        cmdsp.Parameters.Add("Pmsg", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
        dt = MyContext.FillDataTable(cmdsp);


        List<justatest.Models.SalesModel.Sales> details = new List<justatest.Models.SalesModel.Sales>();


        if (cmdsp.Parameters["Pmsg"].Value.ToString() == "T")
        { 

                foreach (DataRow dtrow in dt.Rows)
                {
                    justatest.Models.SalesModel.Sales user = new justatest.Models.SalesModel.Sales();
                    user.Item = dtrow["item"].ToString();
                    user.qty = dtrow["quan"].ToString();
                    user.rate = dtrow["rate"].ToString();
                    user.ppb = dtrow["price_bag"].ToString();
                    details.Add(user);
                }

        }

        var data = details.ToArray();

        return Json(new { data = data}, JsonRequestBehavior.AllowGet);

    }

模型(Sales.cs)

public class Sales
{
    public Sales() { }

    public string Item { get; set; }
    public string Loc { get; set; }
    public Int64 ID { get; set; }
    public Int64 SALES_R_ID { get; set; }
    public Int64 car_IDD { get; set; }
    public Int64 driver_IDD { get; set; }
    public Int64 labor_IDD { get; set; }
    public string qty { get; set; }
    public Int64 t_qty { get; set; }
    public Int64 ship_qty { get; set; }
    public string rate { get; set; }
    public string ppb { get; set; }
    public string inv_lock_id { get; set; }
    public string Nameofcustomer { get; set; }
    public string Descrip { get; set; }

    public DateTime Date { get; set; }
    public Int32 InvoiceID { get; set; }
    public Int32 TotAmount { get; set; }
    public Int32 Disc { get; set; }
    public Int32 GTotal { get; set; }
    public Int32 Customer_Presence { get; set; }
    public Int32 paid { get; set; }
    public Int32 pay_amt { get; set; }
    public Int32 ship { get; set; }
    public Int32 shipamt { get; set; }
    public Int32 trips_no { get; set; }
    public Int32 bags_no { get; set; }


    [Required(ErrorMessage = "Customer Name is Required")]
    public string Customer_Name { get; set; }



    [MaxLength(7)]
    [MinLength(1)]
    [RegularExpression("^[0-9]*$", ErrorMessage = "Loan must be numeric")]
    public string LoanAmount { get; set; }


    [MaxLength(7)]
    [MinLength(1)]
    [RegularExpression("^[0-9]*$", ErrorMessage = "Loan must be numeric")]
    public string ReceivedLoan { get; set; }



    public DataTable GetItems()
    {
        //this.Address = "N/A";
        DataTable dt = new DataTable();
        OracleCommand CmdCommand = new OracleCommand();
        CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
        CmdCommand.CommandText = "Pkg_Inventory.PRC_Shop_Sale_Stock";
        CmdCommand.Parameters.Add("SHOPSALE", OracleType.Cursor).Direction = ParameterDirection.Output;
        CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
        dt = MyContext.FillDataTable(CmdCommand);
        return dt;
    }

    //For Item List

    public System.Web.Mvc.SelectList DT1SelectList(DataTable de, string valueField, string textField, object selectedvalue)
    {
        if (de == null || valueField == null || valueField.Trim().Length == 0
            || textField == null || textField.Trim().Length == 0)
            return null;


        var list = new List<Object>();

        for (int i = 0; i < de.Rows.Count; i++)
        {
            list.Add(new
            {
                value = de.Rows[i][valueField].ToString(),
                text = de.Rows[i][textField].ToString()
            });
        }
        return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
    }

    //For Car

    public System.Web.Mvc.SelectList DT2SelectList(DataTable de, string valueField, string textField, object selectedvalue)
    {
        if (de == null || valueField == null || valueField.Trim().Length == 0
            || textField == null || textField.Trim().Length == 0)
            return null;


        var list = new List<Object>();

        for (int i = 0; i < de.Rows.Count; i++)
        {
            list.Add(new
            {
                value = de.Rows[i][valueField].ToString(),
                text = de.Rows[i][textField].ToString()
            });
        }
        return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
    }

    //For Driver

    public System.Web.Mvc.SelectList DT3SelectList(DataTable de, string valueField, string textField, object selectedvalue)
    {
        if (de == null || valueField == null || valueField.Trim().Length == 0
            || textField == null || textField.Trim().Length == 0)
            return null;


        var list = new List<Object>();

        for (int i = 0; i < de.Rows.Count; i++)
        {
            list.Add(new
            {
                value = de.Rows[i][valueField].ToString(),
                text = de.Rows[i][textField].ToString()
            });
        }
        return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
    }

    //For Labor

    public System.Web.Mvc.SelectList DT4SelectList(DataTable de, string valueField, string textField, object selectedvalue)
    {
        if (de == null || valueField == null || valueField.Trim().Length == 0
            || textField == null || textField.Trim().Length == 0)
            return null;


        var list = new List<Object>();

        for (int i = 0; i < de.Rows.Count; i++)
        {
            list.Add(new
            {
                value = de.Rows[i][valueField].ToString(),
                text = de.Rows[i][textField].ToString()
            });
        }
        return new System.Web.Mvc.SelectList(list.AsEnumerable(), "value", "text", selectedvalue);
    }

    //For sales Invoice

    public DataTable GetInvoice()
    {
        DataTable dt = new DataTable();
        OracleCommand CmdCommand = new OracleCommand();
        CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
        CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Invoice";
        CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
        CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
        CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
        dt = MyContext.FillDataTable(CmdCommand);
        return dt;
    }


    //For sales Details

    public DataTable GetSaleDetails()
    {
        DataTable dt = new DataTable();
        OracleCommand CmdCommand = new OracleCommand();
        CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
        CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Sale_Details";
        CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
        CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
        CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
        dt = MyContext.FillDataTable(CmdCommand);
        return dt;
    }

    //For Item Details

    public DataTable GetItemDetails()
    {
        DataTable dt = new DataTable();
        OracleCommand CmdCommand = new OracleCommand();
        CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
        CmdCommand.CommandText = "Pkg_Sales.Prc_Show_Item_Details";
        CmdCommand.Parameters.Add("SALES_REF_ID", OracleType.Int32, 25).Value = InvoiceID;
        CmdCommand.Parameters.Add("SALECUR", OracleType.Cursor).Direction = ParameterDirection.Output;
        CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
        dt = MyContext.FillDataTable(CmdCommand);
        return dt;
    }

    //For Item Shipment

    public DataTable GetItemShipment()
    {
        DataTable dt = new DataTable();
        OracleCommand CmdCommand = new OracleCommand();
        CmdCommand.CommandType = System.Data.CommandType.StoredProcedure;
        CmdCommand.CommandText = "Pkg_Sales.PRC_Ship_Details";
        CmdCommand.Parameters.Add("SALE_R_ID", OracleType.Int32, 25).Value = InvoiceID;
        CmdCommand.Parameters.Add("SHIPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
        CmdCommand.Parameters.Add("PMSG", OracleType.VarChar, 10).Direction = ParameterDirection.Output;
        dt = MyContext.FillDataTable(CmdCommand);
        return dt;
    }

    public DataTable SaleDetails
    {
        get { return GetSaleDetails(); }
    }

    public DataTable ItemDetails
    {
        get { return GetItemDetails(); }
    }

    public DataTable ItemShipment
    {
        get { return GetItemShipment(); }
    }

    public string JavascriptToRun { get; set; }
}

栈跟踪

<!DOCTYPE html>
<html>
<head>
    <title>A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.</title>
    <meta name="viewport" content="width=device-width" />
    <style>
     body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
     p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
     b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
     H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
     H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
     pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
     .marker {font-weight: bold; color: black;text-decoration: none;}
     .version {color: gray;}
     .error {margin-bottom: 10px;}
     .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
     @media screen and (max-width: 639px) {
      pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
     }
     @media screen and (max-width: 479px) {
      pre { width: 280px; }
     }
    </style>
</head>

<body bgcolor="white">

        <span><H1>Server Error in '/justatest' Application.<hr width=100% size=1 color=silver></H1>

        <h2> <i>A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.</i> </h2></span>

        <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

        <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

        <br><br>

        <b> Exception Details: </b>System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.<br><br>

        <b>Source Error:</b> <br><br>

        <table width=100% bgcolor="#ffffcc">
           <tr>
              <td>
                  <code>

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>

              </td>
           </tr>
        </table>

        <br>

        <b>Stack Trace:</b> <br><br>

        <table width=100% bgcolor="#ffffcc">
           <tr>
              <td>
                  <code><pre>

[InvalidOperationException: A circular reference was detected while serializing an object of type &#39;System.Reflection.RuntimeModule&#39;.]
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1767
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +166
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +793

2 个答案:

答案 0 :(得分:0)

JSON序列化程序不支持的对象层次结构中的循环引用。

你需要有类似的东西:

        return Json(new {
            PropertyA = data.PropertyA,
            PropertyB = data.PropertyB,
            PropertyC = data.PropertyC,
        }, JsonRequestBehavior.AllowGet);

答案 1 :(得分:0)

我用下面的代码解决了这个问题

public async Task<JsonResult> GetAll(int id)
    {
        using (Context context = new Context())
        {
            var menus = context.GetAll(id);

            List<MenuView> menusView = Mapper.Map<List<Menu>, List<MenuView>>(menus);

            //Solve circular reference on JSONResult
            var result = JsonConvert.SerializeObject(menusView, Formatting.Indented,
                       new JsonSerializerSettings
                       {
                           ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                       });

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }

我在我的控件中添加了此代码,在客户端我使用JSON.parse()作为make对象。