如何使用剃刀页面在 ASP.Net Core 上将对象从一个页面传递到另一个页面? [英] How pass objects from one page to another on ASP.Net Core with razor pages?

查看:21
本文介绍了如何使用剃刀页面在 ASP.Net Core 上将对象从一个页面传递到另一个页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有剃刀页面的 Asp.net core 2.0 开发 Web 应用程序.我正在创建一个包含一些数据的对象,并希望将该对象发送到另一个页面.

I'm developing a web application using Asp.net core 2.0 with razor pages. I'm creating an object with some data and want to send that object to another page.

实际上我是这样做的:

var customObject = new{
   //some values
};
return RedirectToPage("NewPage", customObject);

我看到 url 包含我要发送的对象的值,但我找不到如何获取这些值(在 NewPage 实例中).

I see that the url has the values of the object I'm sending, but I can't find how to take that values (in the NewPage instance).

有人知道如何在剃刀页面之间共享对象吗?这是实现它的正确方法吗?或者还有其他更好的方法吗?

Can anybody knows how to share objects between razor pages? Is this the correct way to achieve it? or Is there another better way?

提前致谢

推荐答案

我不知道这是否对你有帮助,或者对于像 Razor 这样的 MVVM 风格来说这是一个很好的实践,但在 ASP.NET Core API 项目中,我经常使用自定义全局 DI 服务,例如

I don't know if that might help you or it is good practice for MVVM flavours like Razor, but inside ASP.NET Core API projects I often use custom global DI'ed services, like

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddSingleton<IMyService, MyService>();

    ...

     services.AddMvc();
}

您可以在 IndexModelCustomModel 之间交换数据,例如.通过将其设置为

You can exchange data between your IndexModel and a CustomModel eg. by setting it like

public class CustomModel : PageModel
{
   public IMyService _myService;

   public CustomModel(IMyService myService)
   {
       _myService = myService;
   }

   public async Task<IActionResult> OnPostAsync(...)
   {
        ...

        _myService.SetDataOrSometing(...);

        ...

        return RedirectToPage();
   }
}

并像检索一样

public class IndexModel : PageModel
{
    public IMyService _myService;

    public IndexModel(IMyService myService)
    {
        _myService = myService;
    }

    public void OnGet()
    {
        var data = _myService.GetDataOrSomething();
    }
}

从这里您还可以使用 ObserveableCollection 并注册事件以将更新记录到您的 PageModels.

From here you can also use an ObserveableCollection and register events to get the updates down to your PageModels.

恕我直言,这是一种将对象从一个页面传递到另一个页面的方法,并且可以清晰地分离关注点.

IMHO this is a way to pass objects from one page to another with a clean separation of concerns.

这篇关于如何使用剃刀页面在 ASP.Net Core 上将对象从一个页面传递到另一个页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆