我正在尝试在“酒店”页面上显示包含酒店名称的字符串列表,但是未显示该列表。我试图将相同的标记放在索引页面上,并且确实可以在该页面上使用。
当前输出如下:
索引页:
酒店页面:
这里是代码部分。欢迎任何想法或建议!
Index.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;
}
}
}
Startup.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?}");
});
}
}
}
site.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;
}
});
}
答案 0 :(得分:0)
设法通过修改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?}");
});