【问题标题】:Razor Pages keep data between class methodsRazor Pages 在类方法之间保留数据
【发布时间】:2018-10-28 16:56:41
【问题描述】:

我最近尝试在剃须刀页面上编写网站时遇到的问题 - 当我在类方法中使用变量时,它不会将这些数据保留在里面。例如:我有一个在创建页面时创建数据的方法。当我按下提交按钮时:类中不会记住数据,因此它返回 null。

我尝试过使用数据绑定、临时数据、私有类。他们都没有将数据保存在一个类中以备将来使用。当前代码是:

`

namespace TestSite.Pages.Shared
{
    public class Registration_2Model : PageModel
    {
        private readonly TestSite.Data.ApplicationDbContext _context;

        public UserManager<IdentityUser> _user;

        public string _ID { get; set; }
        public string _Code { get; set; }

        public bool _Validated;

        public Registration_2Model(UserManager<IdentityUser> UserManager, ApplicationDbContext context)
        {
            _context = context;
            _user = UserManager;
        }

        public IActionResult OnGet()
        {
            var CurrentUser = _context.Simple_User.FirstOrDefault(m => m.ID == Guid.Parse(_user.GetUserId(User)));
            if (CurrentUser == null)
            {
                _ID = _user.GetUserId(User);
                _Code = GenerateCode();
                _Validated = false;

                TempData["ID"] = _ID;
                TempData["Code"] = _Code;

                return Page();
            } else { return Redirect("/Index"); }
        }

        [BindProperty]
        public Simple_User Simple_User { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            Simple_User.ID = Guid.Parse((string)TempData["ID"]);
            Simple_User.Code = (string)TempData["Code"];
            Simple_User.Validated = false;

            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Simple_User.Add(Simple_User);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }

        private string GenerateCode()
        {
            Random _random = new Random();
            return $"{_random.Next(1000, 9999).ToString()}-{DateTime.Now.Year}";
        }
    }
}

`

和 HTML:

`

@{
    ViewData["Title"] = "Second registration";
}

<h2>Second registration</h2>

<h4>One step left. After your initial registration, you must fill in some blanks, after which, our moderator will check and add you to our list.</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label class="control-label">ID</label>
                <input class="form-control" type="text" placeholder="@Model._ID" readonly />
            </div>
            <div class="form-group">
                <label asp-for="Simple_User.Name" class="control-label"></label>
                <input asp-for="Simple_User.Name" class="form-control" />
                <span asp-validation-for="Simple_User.Name" class="text-danger"></span>
                <span asp-validation-for="Simple_User.Code" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label class="control-label">Code</label>
                <input class="form-control" type="text" placeholder="@Model._Code" readonly />
            </div>
            <div class="form-group">
                <label asp-for="Simple_User.Address" class="control-label"></label>
                <input asp-for="Simple_User.Address" class="form-control" />
                <span asp-validation-for="Simple_User.Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

}`

基本上,站点在不可访问的字段中显示一些值,并且在数据库中创建 Simple_User 时应该使用它。但到目前为止我只有空值

【问题讨论】:

  • 哪些数据没有被记住?您的预期行为是什么?
  • _ID 和 _Code。我的预期行为是保留在 onGet() 方法中生成的值,因此我可以在 onPostAsync() 方法中使用它们并使用这些值创建用户。
  • 在表单中有隐藏字段,您可以通过这些隐藏字段通过表单提交传递数据。
  • 隐藏字段可以通过web-console修改。我正在寻找一种用户无法修改的不同方法
  • 那你应该在你的 Httppost 动作中再读一遍,类似于你在 get 中所做的

标签: c# asp.net-core-mvc razor-pages


【解决方案1】:

HTTP 是无状态的™。如果您想在执行一个请求期间设置对象的属性,并让这些值可用于后续请求,您需要实现自己的状态管理策略。

有很多选项可供您使用,具体取决于您想要做什么。如果安全很重要,您应该查看会话变量。同时,以下是所有可用选项:https://www.learnrazorpages.com/razor-pages/state-management

【讨论】:

    【解决方案2】:

    试试scaffolding the pages。您可以丢弃创建/详细信息/删除页面并仅保留编辑页面(如果这是您要查找的内容)。您可以在创建新页面时从命令行或 Visual Studio 中执行此操作。来自 CLI 的类似以下内容(有关详细信息,请参阅 here

    dotnet aspnet-codegenerator razorpage -m SimpleUser -dc ApplicationDbContext
    

    此外,如果您希望在帖子中发送您的 _ID 或 _Code 属性,请将 [BindProperty] 属性添加到它们。有关模型绑定的更多信息,请参阅here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 2021-03-19
      • 2018-06-29
      • 2018-09-02
      • 2013-03-05
      • 2018-04-16
      • 2019-07-28
      相关资源
      最近更新 更多