当ModelState在RegisterForm上无效时,将显示CheckBox值剂量值

时间:2018-08-14 15:44:32

标签: asp.net asp.net-mvc asp.net-mvc-5 checkboxlist

我有一个带有checkBoxOption的注册视图

 <div class="form-group">
                @Html.Label("Whice Console You Play?")
                @for (int i = 0; i < Model.ConsolesCheckBoxList.Count; i++)
                     {

                      @Html.CheckBoxFor(m => Model.ConsolesCheckBoxList[i].IsChecked)
                      @Html.HiddenFor(m => Model.ConsolesCheckBoxList[i].ConsoleId)
                      @Html.DisplayFor(m => Model.ConsolesCheckBoxList[i].ConsoleName)


                    }
            </div>

当这种形式的输入之一不正确或未插入时,将显示ValidationMessageFor并重新显示视图,然后取消复选框的值,为什么?

这是控制器的代码:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register([Bind(Exclude = "UserPhoto")]CommenModel model)
    {
        if (ModelState.IsValid)
        {
            // To convert the user uploaded Photo as Byte Array before save to DB
            byte[] imageData = null;
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase poImgFile = Request.Files["UserPhoto"];

                using (var binary = new BinaryReader(poImgFile.InputStream))
                {
                    imageData = binary.ReadBytes(poImgFile.ContentLength);
                }
            }




            var user = new ApplicationUser
            {
                UserName = model.registerViewModel.Email,
                Email = model.registerViewModel.Email,
                Phone = model.registerViewModel.Phone

            };



            user.UserPhoto = imageData;
            var result = await UserManager.CreateAsync(user, model.registerViewModel.Password);

            //after the user create, we will use the id and add the id to the userAddress table include
            // Address, langitud and latitude.
            using (ApplicationDbContext dbo = new ApplicationDbContext())
            {
                var currentUserId = user.Id;
                var pasinfo = dbo.userAddress.FirstOrDefault(d => d.Userid == currentUserId);

                if (pasinfo == null)
                {
                    pasinfo = dbo.userAddress.Create();
                    pasinfo.Userid = currentUserId;
                    dbo.userAddress.Add(pasinfo);
                }
                pasinfo.Address = model.useraddress.Address;
                pasinfo.latitude = model.useraddress.latitude;
                pasinfo.longitude = model.useraddress.longitude;
                dbo.SaveChanges();

                // now we used foreach loop to check which box is set to true on the view, and if the box set to true
                // we take the id of the boxname and save it in conoleid.
                foreach (var item in model.ConsolesCheckBoxList.Where(x => x.IsChecked).Select(x => x.ConsoleId))
                {
                    var consoleid = item;
                    //here we create a new consoleuserInfo to insert data.
                    var consoleUserInfo = new ConsoleUserInfo
                    {
                        //we insert the id of user, and the consoleid of the checkbox how been marked.
                        Userid = currentUserId,
                        ConsoleId = consoleid


                    };
                    dbo.consoleUserInfo.Add(consoleUserInfo);


                }
                dbo.SaveChanges();

            }


            if (result.Succeeded)
            {

                // await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);


                // Send an email with this link
                 string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                 var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                 await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");

            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

这是我在控制器上的视图:

 // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()

    {
        //using database
        using (ApplicationDbContext dbo = new ApplicationDbContext())
        {
            //data will save list of the consoleCheckBoxItem
            var data = dbo.consolesCheckBox.ToList();
            // because the view is request a common model, we will create new one
            CommenModel a = new CommenModel();
            a.ConsolesCheckBoxList = data;
            //  we will need to return common model, that way we will returen a


            return View(a);

        }
    }

0 个答案:

没有答案