简体   繁体   English

ASP.NET MVC 5 JsonResult和Ajax-MVC JQuery错误

[英]ASP.NET MVC 5 JsonResult & Ajax - MVC JQuery error

Thanks to @NikhilGhuse, which solution have been sent to me (please mark his answer). 感谢@NikhilGhuse,该解决方案已发送给我(请标出他的回答)。 I can apply this solution to my data these are the results and the keys: 我可以将此解决方案应用于我的数据,这些是结果和关键:

First of all my model need to send a List to the controller. 首先,我的模型需要发送一个List到控制器。 This is my my function to send the List: 这是我发送列表的功能:

                            public List<VistaModelo> SegundaConsulta()
                            {
                                //Web.Config
                                Entities db = new Entities();

                                var consulta = from varLocal in db.LecturaContadorLuzAANDRES
                                                group varLocal by varLocal.dispositivo into subconsulta
                                                select subconsulta.OrderByDescending(t => t.unixtime).FirstOrDefault();

                                List<LecturaContadorLuzAANDRES> lista = consulta.ToList();

                                List<VistaModelo> listaVistaModelo = new List<VistaModelo>();


                                foreach (LecturaContadorLuzAANDRES b in lista)
                                {
                                    VistaModelo objLista = b.pasaObjetoAVistaModelo();
                                    listaVistaModelo.Add(objLista);
                                }

                                return listaVistaModelo;
                            }

Then in my controller I need two functions: 然后在我的控制器中,我需要两个功能:

Consulta 6. Read the list and transform to JSON (you need: using Newtonsoft.Json; in the controller: Consulta 6.阅读列表并转换为JSON(您需要:在控制器中使用Newtonsoft.Json ;:

public JsonResult Consulta6()
    {
        var Consulta = new ConsultaContraBD();
        List<VistaModelo> miSegundaConsulta = Consulta.SegundaConsulta();

        return Json(miSegundaConsulta, JsonRequestBehavior.AllowGet); //El JsonRequest Behaviour permite que se devuelva información de JSON en un getRequest.

    }

Consulta7. Consulta7。 From this method I make the View: 通过这种方法,我可以创建视图:

public ActionResult Consulta7()
    {
        return View();

    }

Finally I need Ajax into the script to read the information pass to method Consulta6. 最后,我需要在脚本中使用Ajax来读取传递给Consulta6方法的信息。 Note: Remember to load the packages json2.js and jquery-3.0.0.js 注意:请记住加载包json2.js和jquery-3.0.0.js

                            @{
                            ViewBag.Title = "Consulta7";
                        }



                        <script src="~/Script/jquery-3.0.0.js"></script>
                        <script src="~/Script/json2.js"></script>
                        <script type="text/javascript">

                            $(function () {
                                $('#btonLista').on("click", function (e) {
                                    e.preventDefault();
                                    $.ajax
                                        ({
                                            url: '/Home/Consulta6/',
                                            type: 'get',

                                            dataType: 'json',
                                            success: function (data) {

                                                $(data).each(function (index, item) {
                                                    $('#ulLista').append("<li>" + item.consumo + "</li>")
                                                });
                                            }
                                        });
                                });
                            });
                        </script>
                        <div>
                            <input type="button" id="btonLista" value="Click" name="" />
                            <ul id="ulLista"></ul>
                        </div>

The final result is a page where you click a button and returns the list. 最终结果是一个页面,您单击一个按钮并返回列表。

<script type="text/javascript">
    $(function ()
    {enter code here
        $('#btonLista').on("click", function (e)
        {
            e.preventDefault();
            $.ajax
                ({
                    url: '/Home/Consulta52/',
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        $(data).each(function (index, item) {
                            $('#ulLista').append("<li>"+item.consumo+"</li>")
                        });
                    }
                });
        });
    });
</script>

My two controllers: 我的两个控制器:

public ActionResult Consulta51()
    {
        return View();
    }

    public JsonResult Consulta52()
    {
        var Consulta = new ConsultaContraBD();
        var miSegundaConsulta = Consulta.SegundaConsulta();


        return Json(miSegundaConsulta.ToList(), JsonRequestBehavior.AllowGet);
    }

/// My Sample Starts here ///我的示例从这里开始

//Controller //控制器

     namespace Sample.Controllers
    {
       public class HomeController : Controller
    {
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public JsonResult Consulta52()
    {
        modelCS model = new modelCS();
        List<Department> ds = model.getList();
        return Json(ds, JsonRequestBehavior.AllowGet);
    }
   }
 }

//Index.cshtml //Index.cshtml

     @{
    ViewBag.Title = "Index";
  }
  <h2>
      Index</h2>
  <script src="../../scripts/jquery-2.1.4.js" type="text/javascript">
   </script>
       <script src="../../scripts/json2.js" type="text/javascript"></script>
     <script type="text/javascript">
       $(function () {
    $('#btonLista').on("click", function (e) {
        e.preventDefault();
        $.ajax
            ({
                url: '/Home/Consulta52/',
                type: 'get',

                dataType: 'json',
                success: function (data) {

                    $(data).each(function (index, item) {
                        $('#ulLista').append("<li>" + item.DepartmentName + "</li>")
                    });
                }
            });
         });
       });
  </script>
       <div>
        <input type="button" id="btonLista" value="Click" name="" />
       <ul id="ulLista">
     </ul>
      </div>

And My Model Class goes like this 我的模型课是这样的

    public class modelCS
     {
    string constr = "Data Source=.;Initial Catalog=test1;Integrated Security=True";
    List<Department> newDept = new List<Department>();
    public List<Department> getList()
    {
        SqlConnection con = new SqlConnection(constr);
        // SqlCommand cmd = new SqlCommand("select * from Department", con);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from Department", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        var td = ds.Tables[0];
       // List<Department> newDept = new List<Department>();

        foreach (DataRow t in td.Rows)
        {
            newDept.Add(new Department() { DepartmentId = (int)t.ItemArray[0], DepartmentName = t.ItemArray[1].ToString() });
        }

        return newDept;
        //List<string> list = listT
    }

}

Department class 部门课

public class Department
{
    public int DepartmentId { get; set; }
    public string DepartmentName { get; set; }
}

产量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM