簡體   English   中英

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

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

我試圖在“酒店”頁面上顯示包含酒店名稱的字符串列表,但是未顯示該列表。 我試圖將相同的標記放在索引頁面上,並且確實可以在該頁面上使用。

目前的輸出是這樣的:

索引頁:

在此處輸入圖片說明

酒店頁面:

在此處輸入圖片說明

這是代碼部分。 歡迎任何想法或建議!

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;
    }
});
}

設法通過修改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?}");
        });  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM