我开始知道Razor页面只适用于从PageModel子类化的模型。所以我故意在生成的剃刀页面的“代码隐藏”中创建这个类。我实例化这个类并将其传递给Page,“Model”仍为NULL。 控制器:
[HttpGet]
public ActionResult Index()
{
long count = _service.GetData();
IndexModel model = new IndexModel(_service.GetSortedData());
return View("~/Pages/MyPage/Index.cshtml", model);
}
页:
@page
@using MyNamespace
@model MyNamespace.IndexModel
@foreach (var data in Model.Data) <= Model is NULL
<snip>
感谢任何建议和见解。
答案 0 :(得分:0)
以下示例将帮助您了解什么是剃刀页面。
什么是Razor页面?
Razor Pages是ASP.NET Core MVC的一项新功能,它使编写以页面为中心的场景更容易,更高效。 (定义来自 - https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-pages/?tabs=visual-studio)
哪里使用Razor页面?
应用程序中有一些页面不太大,你仍然需要创建一个控制器并添加动作方法,以及我们需要添加View。
在这部分我们可以使用Razor Pages,后面有代码,我们只需要添加一个Razor页面,在视图“Customer.cshtml”上你可以设计你的视图,你可以在同一页面上编写代码处理诸如Get和Post之类的请求。但是,如果您认为要将其分开,那么您可以使用“Customer.cshtml.cs”后面的代码
为模型
指定值时的代码片段using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPagesDemo.Models;
using System.Collections.Generic;
using System.Linq;
namespace RazorPagesDemo.Pages
{
public class AllCustomerModel : PageModel
{
DatabaseContext _Context;
public AllCustomerModel(DatabaseContext databasecontext)
{
_Context = databasecontext;
}
public List<Customer> CustomerList { get; set; }
public void OnGet()
{
// Assigning value to Model
var data = (from customerlist in _Context.CustomerTB
select customerlist).ToList();
CustomerList = data;
}
}
}
查看模型用于显示数据的位置。
@page
@using RazorPagesDemo.Models
@model AllCustomerModel
<h2>Index</h2>
<p>
<a asp-page="Customer">Create New Customer</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayName("Name")
</th>
<th>
@Html.DisplayName("Address")
</th>
<th>
@Html.DisplayName("Country")
</th>
<th>
@Html.DisplayName("City")
</th>
<th>
@Html.DisplayName("Phoneno")
</th>
<th>Edit | Delete</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.CustomerList)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Country)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.Phoneno)
</td>
<td>
<a asp-page="./EditCustomer" asp-route-id="@item.CustomerID">Edit</a> |
<a asp-page="./AllCustomer" onclick="return confirm('Are you sure you want to delete this item?');" asp-page-handler="Delete" asp-route-id="@item.CustomerID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
详情文章的链接: - Link for Complete Article
答案 1 :(得分:-1)
好老&#34;控制器&#34;离开了。它全都在&#34; Code-behind&#34;页面。