Search code examples
asp.net-coreviewasp.net-core-mvcviewmodel

Attempting to set view field to a string, but string is not being submitted


To give some background, I am attempting to set a temporary password for an account that will be required to be changed on login.

I am creating the "Random string" and I am setting it to a ViewBag variable here:

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

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

            return View();
        }

I am setting the value of the Password field to this variable to view in plaintext (disabled so the field cannot be altered).

            <!-- 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>

When I am submitting the form I am getting a validation error stating that "The Password field is required." Is there some interaction that I am missing? because I am able to see this value in the view, so my thoughts are that it would be submitting with the form along with the rest of the fields (Pertinent ViewModel property below).

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

Solution

  • Please note that disabled elements in a form will not be submitted. You can try to make it readonly, like below.

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