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

查看:82
本文介绍了如何在带有剃须刀页面的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'ed服务,例如

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天全站免登陆