c# - ASP.NET Core 2.1 - 在特定 html 页面上显示字符串列表
问题描述
我试图在“酒店”页面上显示包含酒店名称的字符串列表,但是,该列表没有显示。我试图在索引页面上放置相同的标记,并且它确实在该页面上工作。
目前的输出是这样的:
索引页面:
酒店页面:
这是代码部分。欢迎任何想法或建议!
索引.cshtml:
@{
ViewData["Title"] = "Home Page";
}
<table>
<tbody id="hotels">Hotels:</tbody>
</table>
Hotels.cshtml:
@{
ViewData["Title"] = "Hotels";
}
<table>
<tbody id="hotels">Hotels:</tbody>
</table>
<ul id="dummy"></ul>
HomeController.cs:
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using VIABooking.Models;
namespace VIABooking.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Hotel()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
HotelController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VIABooking.Models;
namespace VIABooking.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HotelController : ControllerBase
{
private readonly DatabaseContext _context;
public HotelController(DatabaseContext context)
{
_context = context;
if (_context.HotelItems.Count() == 0)
{
_context.HotelItems.Add(new Hotel { Name = "Hotel Ritz Aarhus", RoomNum = 56 });
_context.HotelItems.Add(new Hotel { Name = "Scandic Copenhagen", RoomNum = 72 });
_context.HotelItems.Add(new Hotel { Name = "Hotel Villa Provence", RoomNum = 86 });
_context.HotelItems.Add(new Hotel { Name = "First Hotel Atlantic", RoomNum = 132 });
_context.SaveChanges();
}
}
[HttpGet]
public ActionResult<List<Hotel>> GetAll()
{
return _context.HotelItems.ToList();
}
[HttpGet("{id}", Name = "GetHotel")]
public ActionResult<Hotel> GetById(long id)
{
var hotel = _context.HotelItems.Find(id);
if (hotel == null)
{
return NotFound();
}
return hotel;
}
}
}
启动.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using VIABooking.Models;
namespace VIABooking
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DatabaseContext>(opt => opt.UseInMemoryDatabase("HotelList"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
网站.js:
const uri = "api/hotel";
let hotels = null;
$(document).ready(function () {
getData();
$('#dummy').append("<li>Test1</li>");
$('#dummy').append("<li>Test2</li>"); });
function getData() {
$.ajax({
type: "GET",
url: uri,
cache: false,
success: function (data) {
const tBody = $('#hotels');
$(tBody).empty();
$.each(data, function (key, item) {
const tr = $("<tr></tr>")
.append($("<td></td>").text(item.name));
tr.appendTo(tBody);
});
hotels = data;
}
});
}
解决方案
通过像这样修改site.js设法解决了这个问题:
来自:const uri = "api/hotel";
至: const uri = "/api/hotel";
Startup.cs 像这样:
从:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
至:
app.UseMvc(routes =>
{
routes.MapRoute("hotels", "{area:exists}/{controller=Hotel}/{action=GetAll}/{id}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});