在上个月的 ASP CORE 2.0 新版本中,他们引入了 Razor Pages,这让我陷入了困境,因为 ASP CORE 2 Razor 页面中缺少旧 Controller 和模型 frpm MVC。
我由此的理解page是我们使用 Action/Method 外部的 [BindProperty] 属性
获得属性的默认绑定(bind)!!!!,这是因为它已转移到 MVVM 框架
,而不是MVC
框架。
- 问题:在尝试重写传统操作时,由于没有 Controller ,如何将代码转移到新的 RazorPages MVVM 框架,即 在哪里以及如何绑定(bind)属性和操作/处理程序?
- 由于属性不在签名中,操作/处理程序如何知道哪些属性从 View /Razor 页面传递给它?
什么是页面模型?
public class CreateModel : PageModel // what is this pagemodel, is it new or the same old model?
{
private readonly AppDbContext _db;
public CreateModel(AppDbContext db)
{
_db = db;
}
[BindProperty]
public Customer Customer { get; set; } // why is the property outside?
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_db.Customers.Add(Customer);
await _db.SaveChangesAsync();
return RedirectToPage("/Index");
}
}
最佳答案
根据我的理解,Razor 页面几乎是旧的 asp.net 表单的替代品,在旧的 asp.net 表单中,您只需拥有一个带有逻辑的页面。有点像 php 的工作方式。
如果您创建一个页面,假设 Pages/Index2.cshtml
您还应该创建(或者可能在 Visual Studio 中为您创建)一个名为 Pages/Index2.cshtml.cs
的“代码隐藏”文件。例如。
// The page file
@page
@using RazorPages
@model IndexModel2
<h2>Separate page model</h2>
<p>
@Model.Message
</p>
// The code-behind file
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
namespace RazorPages
{
public class IndexModel2 : PageModel
{
public string Message { get; private set; } = "PageModel in C#";
public void OnGet()
{
Message += $" Server time is { DateTime.Now }";
}
}
}
您仍然可以拥有模型并在代码隐藏文件中初始化它们。但如果你想要 Controller ,我建议你不要使用razor页面,而只使用经典的mvc。您可以用它创建一个新项目,只是不要从模板中选择 Razor 页面。 您当然不需要创建 Razor Pages 项目。这只是一个选项。我个人并没有真正使用它,因为我认为很容易重复代码,因为每个代码隐藏文件仅对一页有效。
What is the PageModel?
页面模型只是代码隐藏文件,它为您的特定页面执行服务器端逻辑。
我不确定您到底在要求什么,您像代码隐藏类中的任何其他 Razor 页面和属性一样绑定(bind)模型。在我的示例中,该模型是代码隐藏文件。
how does the action/handler know which properties were passed to it from the View/Razor Page?
操作处理程序通过您在 Razor 页面中指定它来了解它:
<input asp-for="Customer.Name" />
请在此处阅读有关 Razor Pages 的更多信息: https://learn.microsoft.com/en-us/aspnet/core/mvc/razor-pages/?tabs=visual-studio
关于asp.net-mvc - 如何将 MVC 操作和属性重写为 ASP Core MVVM Razor 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46210835/