繁体   English   中英

无法从控制器获取数据作为json

[英]Can't get data from controller as json

我需要将数据从控制器以JSON格式获取到View,但是它不起作用,我也不知道为什么。

我的控制器(我在index操作上请求它):

    public class HomeController : Controller
    {
        CompanyTicketsDb _db = new CompanyTicketsDb();

        public ActionResult Index()
        {
            var model =
                _db.Tickets
                    .Select(r => new TicketListViewModel
                    {
                        Id = r.Id,
                        Name = r.Name,
                        Description = r.Description,
                        CompanyName = r.CompanyName,
                        Status = r.Status,
                        CompanyId = r.CompanyId,
                    });
            if (Request.AcceptTypes.Contains("application/json"))
            {
                return Json(model, JsonRequestBehavior.AllowGet );
            } 

            return View(model);
        }
    }

我的视图(是局部视图)看起来很像(测试模式):

@model IEnumerable<MvcApplication4.Models.TicketListViewModel>

<button id="Button1">asd</button>

@section scripts {
<script src="~/Scripts/knockout-3.2.0.js"></script>
    <script>
        $(document).ready(function () {
            $("#Button1").click(function (evt) {
                type: 'GET'
                url = '/';
                dataType = 'json';
                contentType = 'application/json';
                success = function (data) {
                    alert(data);
                    console.log("asd");
                };
                error = function () { alert("Error retrieving employee data!"); };

            });
        });

    </script>

}

事实是,我没有收到任何消息(也不发送警报或控制台日志)来测试返回的JSON是否有效,因此之后我可以使用它们来填充View。

因为您的语法错误。 您正在使用“ =”,但应使用“:”。

@model IEnumerable<MvcApplication4.Models.TicketListViewModel>

<button id="Button1">asd</button>

@section scripts {
<script src="~/Scripts/knockout-3.2.0.js"></script>
<script>
    $(document).ready(function () {
        $("#Button1").click(function (evt) {
            $.ajax({
                type: 'GET'
                url : '/';
                dataType : 'json';
                contentType : 'application/json';
                success : function (data) {
                alert(data);
                console.log("asd");
            };
            error : function () { alert("Error retrieving employee data!"); };

        });
    });

</script>

}

暂无
暂无

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

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