在剃刀页面中传递对象的最简单方法

时间:2021-01-05 03:09:47

标签: asp.net-core razor razor-pages

我是 Razor 的新手,我正在尝试将数据从“Index.html”传递到“Quiz.html”,但我正在努力使用不同的教程将这些片段组合在一起。这是我到目前为止的地方。我正在尝试在不使用服务的情况下执行此操作,但不确定是否可行。

谢谢!

索引.html

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome, @Model.Name</h1>
    <p>This is My Quiz App</a>.</p>
    <form method="post">
        <label>What's your name?</label>
        <input type="text" asp-for="@Model.Visitor.Name">
        <button type="submit">Send</button>
    </form>
</div>

索引.cs

    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        [ViewData]
        [BindProperty]
        public string Name { get; set; }
        public Visitor Visitor { get; set; }

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
           Name = "Stranger";
        }

          public IActionResult OnPost()
        {
            return RedirectToPage("/Quiz", new { Visitor.Name }); 
        }
    }
}

测验.html

@page
@model QuizModel
@{
    ViewData["Title"] = "Quiz Page";
}

<div class="text-center">
    <h1 class="display-4">Thanks for checking my first website out, @Model.Name. Are you ready?</h1>
    <p>Let's see how much you know about me.</a>.</p>
</div>

测验.cs

 public class QuizModel : PageModel
    {
        [ViewData]
        [BindProperty]
        public string Name { get; set; }
        public Visitor Visitor { get; set; }

        public void OnGet()
        {
            Name = ?
        }

1 个答案:

答案 0 :(得分:1)

您可以使用 asp-page 标签助手直接将 Index.cshtml 中的表单提交到 Quiz.cs。在 OnPost

中定义一个 Quiz.cs 处理程序
public class QuizModel : PageModel
{
    [ViewData]
    [BindProperty]
    public string Name { get; set; }

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

    public void OnGet()
    {
        
    }

    public void OnPost()
    {
        Name = Visitor.Name;
    }
}

Index.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome, @Model.Name</h1>
    <p>This is My Quiz App.</p>
    <form asp-page="Quiz" method="post">
        <label>What's your name?</label>
        <input type="text" asp-for="Visitor.Name">
        <button type="submit">Send</button>
    </form>
</div>

结果:

enter image description here

相关问题