Asp. net MVC проверка не работает, скорее выдает исключение - PullRequest
0 голосов
/ 27 апреля 2020

Я пытаюсь создать форму регистрации для MVC веб-приложения, но по какой-то причине проверка не работает, компилятор пропускает if(modelstate.isvalid), а затем выдает исключение на password hashing, поскольку значение null .

Я на самом деле пытаюсь скопировать код из другого проекта, так как у меня были проблемы с обновлением локальных данных, код почти такой же, но проверка не работает, я не знаю, могу ли я я не знаю о какой-то другой проблеме

Это контроллер

namespace TestApp6.Controllers
{
    public class UserController : Controller
    {
        //Registration action
        [HttpGet]

        public ActionResult Registration()
        {
            return View();
        }

        //Registration POST action
        [HttpPost]
        [ValidateAntiForgeryToken]

        public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user)
        {
            bool Status = false;
            string message = "";

            //
            // Model Validation
            if (ModelState.IsValid)
            {





                // Generate Activation code
                user.ActivationCode = Guid.NewGuid();


                //Password hashing
                user.Password = Crypto.Hash(user.Password);
                user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword);

                user.IsEmailVerifed = false;




                //Save data to database

                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    dc.Users.Add(user);
                    dc.SaveChanges();

                    // send Email to the user

                    //SendVerificationSendLink(user.EmailID, user.ActivationCode.ToString());
                    //message = "Registration successfully done.Account activation link" +
                    //    " has been sent to your email id:" + user.EmailID;
                    //Status = true;
                }



            }

            else
            {
                message = "Invalid Request";
            }

            ViewBag.Message = message;
            ViewBag.Status = Status;
            return View(user);



        }

Модель

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
//namespace RegistrationAndLogin.Models.Extended

namespace TestApp6.Models
{

    [MetadataType(typeof(UserMetaData))]
    public partial class User
    {
        public string ConfirmPassword { get; set; }
    }

    public class UserMetaData
    {



        public class UserMetadata
        {
            [Key]
            public string UserID { get; set; }

            [Display(Name = "Username")]
            [Required(AllowEmptyStrings = false, ErrorMessage = "Username required")]
            public string Username { get; set; }

            [Display(Name = "Email ID")]
            [Required(AllowEmptyStrings = false, ErrorMessage = "Email ID required")]
            [DataType(DataType.EmailAddress)]
            public string EmailID { get; set; }

            [Required(AllowEmptyStrings = false, ErrorMessage = "Password is required")]
            [DataType(DataType.Password)]
            [MinLength(6, ErrorMessage = "Minimum 6 characters required")]
            public string Password { get; set; }

            [Display(Name = "Confirm Password")]
            [DataType(DataType.Password)]
            [Compare("Password", ErrorMessage = "Confirm password and password do not match")]
            public string ConfirmPassword { get; set; }

            [Display(Name = "Favorite Tag")]
            public FavoriteTag FavoriteTag { get; set; }

            [Display(Name = "UserPhoto")]
            public byte[] UserPhoto { get; set; }
        }
    }
}

Вид

@model TestApp6.Models.User

@{
    /**/

    ViewBag.Title = "Registration";
}

<h2>Registration</h2>



@if (ViewBag.Status != null && Convert.ToBoolean(ViewBag.Status))
{
    if (ViewBag.Message != null)
    {
        <div class="alert alert-success">
            <strong>Success!</strong>@ViewBag.Message
        </div>
    }

}

else
{
    using (Html.BeginForm("Registration", "User", FormMethod.Post, new
    {
        @class = "form-horizontal",
        role = "form",
        enctype = "multipart/form-data"
    }))
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">

            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
                </div>
            </div>



            <div class="form-group">
                @Html.LabelFor(model => model.EmailID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.EmailID, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.EmailID, "", new { @class = "text-danger" })
                    @Html.ValidationMessage("EmailExist", new { @class = "text-danger" })
                </div>
            </div>



            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
                </div>
            </div>

            @*<div class="form-group">
                    @Html.LabelFor(m => m.UserPhoto, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">

                        <input type="file" name="UserPhoto" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />

                    </div>
                </div>*@










            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>


        // So if the message is different then null
        // then we get error message
        if (ViewBag.Message != null)
        {
            <div class="alert alert-danger">
                <strong>Error!</strong>@ViewBag.Message
            </div>
        }

    }
}






<div>
    @Html.ActionLink("Login", "Login")
</div>

@section Scripts {
    <script src="~/Scripts/jquery.js"></script>
    <script src="~/Scripts/jquery.validation.js"></script>
    <script src="~/Scripts/jquery.validation.unobtrusive.js"></script>
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...