【发布时间】:2020-02-01 17:53:28
【问题描述】:
我更改了 Person 控制器和 Home 视图。
我在数据库中有 209 个人。这就是它在“个人”视图中向我展示的方式。
当我中断代码计数时,我显示为 0。
查看主页: 我这里也做了修改。
@model Legolandia.Models.Store
@{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<div class="row">
@section Scripts {
<script>
// document.ready is fired once the page has loaded in the browser
$(document).ready(function () {
// set the url to get the data from the PersonController
var url = '@Url.Action("GetPersonCount", "Person")';
// use jQuery.getJSON to get our data from the controller
$.getJSON(url, function(data) {
// update the element with the count from the controller
$('#personCount').text(data.count);
});
});
</script>
}
<div id="orange" class="col-md-4">
<a class="change-a" href="/Person/Index">
<div class="change-title">
Person in system: <span id="personCount"></span>
</div>
控制人:
我也在这里做了修改。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Legolandia.Models;
namespace Legolandia.Controllers
{
public class PersonController : Controller
{
private LegolandEntities db = new LegolandEntities();
// GET: Person
public ActionResult Index()
{
var person = db.Person.Include(o => o.xxx);
ViewBag.PersonCount = db.Person.Count();
return View(person.ToList());
}
public ActionResult GetPersonCount()
{
var count = db.Person.Count(); // get count from database
var data = new { count }; // anonymous type
return Json(data); // return serialized Json data
}
【问题讨论】:
-
抱歉,我没有保存更改。但是,它仍然不起作用。在 Person/Index.cshtml 中,我使用:“在系统中:@Model.Count()。它可以工作。
-
您能确认 jQuery 已添加到您的网站吗?您能否确认您没有收到任何错误(javascript 和 C#)?
-
我没有任何关于错误的信息。
-
要查看 javascript 错误,请打开浏览器调试器(在“主页/索引”上按 F12)并转到控制台查看错误。
-
你是对的。问题在于:“JsonRequestBehavior。AllowGet 不适用于 HttpGet”。我在控制器中更改为:“return Json (data, JsonRequestBehavior.AllowGet); 现在一切正常。非常感谢您的帮助。您很棒。
标签: c# asp.net-mvc