【问题标题】:Attempting to set view field to a string, but string is not being submitted尝试将视图字段设置为字符串,但未提交字符串
【发布时间】:2021-01-08 02:12:06
【问题描述】:

为了提供一些背景知识,我正在尝试为一个需要在登录时更改的帐户设置一个临时密码。

我正在创建“随机字符串”,并在此处将其设置为 ViewBag 变量:

        public IActionResult CreateAdminAccount()
        {
            Random rng = new Random();
            var num = rng.Next(1, 100);

            ViewBag.Password = "Administrator" + num + "!";

            return View();
        }

我将Password 字段的值设置为该变量,以便以纯文本形式查看(已禁用,因此无法更改该字段)。

            <!-- rest of form omitted for brevity -->

            <div class="form-group">
                <label asp-for="Password" class="control-label"></label>
                <input asp-for="Password" class="form-control" value="@ViewBag.Password" disabled />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>

当我提交表单时,我收到一个验证错误,指出“密码字段是必需的”。我缺少一些互动吗?因为我能够在视图中看到这个值,所以我的想法是它将与表单以及其余字段一起提交(下面的相关 ViewModel 属性)。

        [Required]
        public string Password { get; set; }

【问题讨论】:

    标签: asp.net-core view asp.net-core-mvc viewmodel


    【解决方案1】:

    请注意,表单中的禁用元素将不会被提交。您可以尝试将其设为只读,如下所示。

    <input asp-for="Password" class="form-control" value="@ViewBag.Password" readonly />
    

    【讨论】:

    • 啊,好吧,这只是一个简单的疏忽……非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 2016-09-01
    相关资源
    最近更新 更多