【问题标题】:How can i do multiple routes in aspnetcore razorpages with database values如何在具有数据库值的 asp net core razor 页面中执行多个路由
【发布时间】:2020-01-04 14:56:26
【问题描述】:

我想用我的类别创建特定的路线。我有一个类别,例如“笔记本电脑、手机、相机、音响系统等”。

我为显示类别详细信息创建了名为 CategoryDe​​tail 的页面。我想为每个类别创建带有约定的路线。 例如;

mysite.com/laptops
mysite.com/sound-systems

我写了以下代码。

services.AddMvc()
                .AddRazorPagesOptions(options =>
                {
                    var categories = new[] { "laptops", "sound-systems" };
                    foreach (var category in categories)
                    {
                        options.Conventions.AddPageRoute("/CategoryDetail", $"/{category}");
                    }
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

此代码为每个类别创建路线,但我没有在 CategoryDe​​tail 页面中访问类别名称。

CategoryDe​​tailPage.cs

public class CategoryDetailModel : PageModel
    {
        public void OnGet()
        {
            string category = ???;
        }
    }

【问题讨论】:

  • 您在标题中谈论在路由配置中使用数据库值。我在您的代码中没有看到它。您是否添加了类别数组以简化代码?你如何调用你的数据库?
  • 对不起,我的类别来自数据库(我确实为此编写了数据库值),但在这段代码中,我确实编写为模拟(var categories = ...)。我的问题与路线创建有关...

标签: asp.net-core routing razor-pages


【解决方案1】:

我为显示类别详细信息创建了名为 CategoryDe​​tail 的页面。我想为每个类别创建带有约定的路线。例如;

mysite.com/laptops

mysite.com/sound-systems

尝试使用[BindProperty] 属性。 [BindProperty] 绑定与属性同名的表单值和查询字符串。 (SupportsGet = true) 是绑定 GET 请求所必需的。

不清楚发送类别的页面的设计,以下是一个工作演示,您可以参考并根据需要进行修改。

索引.cshtml

@page
@model RazorPages2_2Test.Pages.Peoples.IndexModel

<table class="table">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Person[0].Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Person[0].Age)
        </th>
        <th></th>
    </tr>
</thead>
<tbody>
@foreach (var item in Model.Person) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
        <td>

            <a asp-page="./PersonDetails" asp-route-Name="@item.Name">PersonDetails</a>
        </td>
    </tr>
}
</tbody>
</table>

PersonDetailsModel

public class PersonDetailsModel : PageModel
{
    [BindProperty(SupportsGet = true)]
    public string Name { get; set; }
    public void OnGet()
    {
        string name = Name;
    }
}

上面代码得到的路由是/Peoples/PersonDetails?Name=Sherry,将.cshtml文件中@page指令中的路由模板改成路由/Peoples/PersonDetails/Sherry如下所示

@page "{Name?}"
@model RazorPages2_2Test.Pages.Peoples.PersonDetailsModel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2020-12-21
    • 2019-12-20
    相关资源
    最近更新 更多