【问题标题】:asp.net core razor pages onpost set value of textboxasp.net core razor pages onpost设置文本框的值
【发布时间】:2020-11-18 12:14:03
【问题描述】:

我是 asp.net 核心的新手,我正在使用基本的 razor 页面并尝试通过提交按钮发布 onpost,然后将绑定到页面的公共属性设置为来自 onpost 的特定值。下面是我的代码。但是当我点击提交按钮时,帖子会发生但没有任何更新?当在 OnPost 中将 test1 设置为“这应该可以工作”时,我如何才能在文本框中的页面上获取它?

索引.cshtml

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

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<form method="post">
    <label>testing</label>
    <input asp-for="@Model.test1" type="text" />
    <br />
    <br />
    <input id="Submit1" type="submit" value="submit" />

</form>

然后是我的 Index.cshtml.cs

namespace WebApplication1.Pages
{
    [BindProperties]
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

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

     
        public string test1 { get; set; }

        public void OnGet()
        {
            
         
        }

        public IActionResult OnPost()
        {

            test1 = "this should work";

            return Page();
        }



    }
}

【问题讨论】:

    标签: asp.net asp.net-core


    【解决方案1】:

    但是当我点击提交按钮时,帖子会发生但什么也没有 得到更新?当它在 OnPost 中设置为时,我如何获得 test1 “这应该可以工作”回到文本框中的页面上?

    要解决这个问题,你应该将值属性绑定到输入控件,如下:

     <input asp-for="@Model.test1" type="text"  value="@Model.test1"/>
    

    你可以参考这个link

    这是测试结果:

    【讨论】:

    • 谢谢!我现在觉得自己像个笨蛋。我已经做了多年的 winform 编程,刚刚在 asp.net 上进行 web 编程,在过去的 2 个月内才进入 asp.net core :),我完全没有这样想,谢谢你的帮助。跨度>
    • @johnjohnson,如果这可以帮助您解决问题,请接受它作为答案。这将帮助有相同问题的其他人更容易找到答案。
    猜你喜欢
    • 1970-01-01
    • 2018-10-29
    • 2021-05-22
    • 2021-07-27
    • 2020-11-21
    • 2018-03-30
    • 2018-09-12
    • 2019-02-26
    • 2018-10-16
    相关资源
    最近更新 更多