简体   繁体   English

ASP.NET Core 2.1-在特定的html页面上显示字符串列表

[英]ASP.NET Core 2.1 - Displaying a list of strings on a specific html page

I am trying to display a list of strings containing hotel names on a "Hotels" page, however, the list does not get shown. 我试图在“酒店”页面上显示包含酒店名称的字符串列表,但是未显示该列表。 I have tried to put same markup on the index page, and it does work on that page. 我试图将相同的标记放在索引页面上,并且确实可以在该页面上使用。

Output is like this at the moment: 目前的输出是这样的:

Index page: 索引页:

在此处输入图片说明

Hotels page: 酒店页面:

在此处输入图片说明

Here are the code parts. 这是代码部分。 Any ideas or suggestions are welcomed! 欢迎任何想法或建议!

Index.cshtml: Index.cshtml:

@{
  ViewData["Title"] = "Home Page";
 }

<table>
   <tbody id="hotels">Hotels:</tbody>
</table>

Hotels.cshtml: Hotels.cshtml:

@{
ViewData["Title"] = "Hotels";
}

<table>
    <tbody id="hotels">Hotels:</tbody>
</table>

<ul id="dummy"></ul>

HomeController.cs: 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: 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: 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: 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;
    }
});
}

Managed to solve the problem by modifying the site.js like this: 设法通过修改site.js来解决问题,如下所示:

From: const uri = "api/hotel"; 来自:const uri =“ api / hotel”;

To: const uri = "/api/hotel"; 收件人:const uri =“ / api / hotel”;

And Startup.cs like this: 像这样的Startup.cs:

From: 从:

app.UseMvc(routes =>
            {                
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

To: 至:

app.UseMvc(routes =>
        {
            routes.MapRoute("hotels", "{area:exists}/{controller=Hotel}/{action=GetAll}/{id}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });  

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

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