由用户代码

时间:2016-07-20 14:23:55

标签: c# nullreferenceexception html.dropdownlistfor

此消息

"Object reference not set to an instance of an object"
当我注册为现有用户名并将此下拉列表视为错误时,发生了

。如何捕获此错误消息?

@Html.DropDownListFor(a => a.BrcId, new SelectList(Model.Branches, "BrcId", "BranchName"), "Select Branch")

我有一个RegisterModel类

public class RegisterModel
    {
        [Required]
        [Display(Name="Branch Name")]
        public int? BrcId { get; set; }

        [Required]
        [Display(Name="User Name")]
        public string UserName { get; set; }

        [Required]
        [Display(Name="Password")]
        [DataType(DataType.Password)]
        [StringLength(20, ErrorMessage="The {0} must be at least {2} characters long.", MinimumLength=6)]
        public string Password { get; set; }

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

        [Required]
        [Display(Name="LastName")]
        public string LastName { get; set; }

        [Required]
        [Display(Name="First/Middle Name")]
        public string FirstMidName { get; set; }

        [Required]
        [Display(Name="Gender")]
        public string Gender { get; set; }

        [Required]
        [Display(Name="Date of Birth")]
        [DataType(DataType.DateTime)]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DateOfBirth { get; set; }

        [Required]
        [Display(Name="Telephone")]
        [DataType(DataType.PhoneNumber)]
        [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:(###) ###-####}")]
        public string Telephone { get; set; }

        [Required]
        [Display(Name="Email")]
        [RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "Please enter correct email address")]
        public string Email { get; set; }

        [Required]
        [Display(Name="Secret Question")]
        public string SecretQuestion { get; set; }

        [Required]
        [Display(Name="Secret Answer")]
        public string SecretAnswer { get; set; }

        [Required]
        [Display(Name="Status")]
        public string Status { get; set; }

        [Required]
        [Display(Name="Role")]
        public string Role { get; set; }

        [Required]
        [Display(Name = "Created By")]
        public string CreatedBy { get; set; }

        [Required]
        [Display(Name = "Created Date")]
        [DataType(DataType.DateTime)]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public DateTime CreatedDate { get; set; }

        public IEnumerable<Branch> Branches { get; set; }        
    }

和一个名为&#34; BasedController&#34;其中包含一个动作方法

[Authorize]
    public ActionResult Register()
    {
        var model = new RegisterModel
        {
            Branches = _db.Branch.ToList()
        };
        _db.Dispose();
        return View(model);
    }

[HttpPost]        
        [ValidateAntiForgeryToken]
        public ActionResult Register(
            [Bind(Include=
                "BrcId, UserName, Password, LastName, FirstMidName, Gender, DateOfBirth, Telephone, Email, SecretQuestion, SecretAnswer, Status, Role, CreatedBy, CreatedDate")]
                    User entry, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var Obj = _db.User.Where(u => u.UserName.Equals(entry.UserName)).FirstOrDefault();
                    if (Obj == null) //if current user doesn't exist
                    {
                        // Attempt to register the user
                        _db.User.Add(entry);
                        _db.SaveChanges();
                        _db.Dispose();
                        ModelState.Clear();
                        return RedirectToAction("Login");
                    }
                    else
                    {
                        ModelState.AddModelError("", "username is already registerd");
                        return View();
                    }
                }
            }
            catch (Exception e)
            {
                ViewBag.ErrorMessage = e.Message.ToString();
                return View("Error");
                //ModelState.AddModelError("", e.Message);
            }            
            return View();
        }

和一个名为&#34; Register.cshtml&#34;

的视图
@using (Html.BeginForm()) {
        @Html.AntiForgeryToken()


        <table>
            @Html.ValidationSummary(true)
        <tr>
            <td>
                @Html.LabelFor(a => a.BrcId)
            </td>
            <td>                 
                @Html.DropDownListFor(a => a.BrcId, new SelectList(Model.Branches, "BrcId", "BranchName"), "Select Branch")
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.BrcId)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.UserName)
            </td>
            <td>
                @Html.TextBoxFor(a => a.UserName)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.UserName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.Password)
            </td>
            <td>
                @Html.PasswordFor(a => a.Password)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.ConfirmPassword)
            </td>
            <td>
                @Html.PasswordFor(a => a.ConfirmPassword)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.ConfirmPassword)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.LastName)
            </td>
            <td>
                @Html.TextBoxFor(a => a.LastName)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.LastName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.FirstMidName)
            </td>
            <td>
                @Html.TextBoxFor(a => a.FirstMidName)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.FirstMidName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.Gender)
            </td>
            <td>
                @Html.DropDownListFor(a => a.Gender, new List<SelectListItem> 
                {
                    new SelectListItem{Text="Male"},
                    new SelectListItem{Text="Female"}
                },"Select Gender")
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.Gender)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.DateOfBirth)
            </td>
            <td>
                @Html.EditorFor(a => a.DateOfBirth)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.DateOfBirth)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.Telephone)
            </td>
            <td>
                @Html.EditorFor(a => a.Telephone)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.Telephone)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.Email)
            </td>
            <td>
                @Html.TextBoxFor(a => a.Email)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.Email)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.SecretQuestion)
            </td>
            <td>
                @Html.DropDownListFor(a => a.SecretQuestion, new List<SelectListItem> 
                {
                    new SelectListItem{Text = "Where is the first place, you met your crush?"},
                    new SelectListItem{Text = "Who is your favorite teacher?"},
                    new SelectListItem{Text = "Where is your dream place?"},
                    new SelectListItem{Text = "What is your favorite color?"},
                    new SelectListItem{Text = "What is your favorite food?"},
                    new SelectListItem{Text = "What is your pet's name?"},
                    new SelectListItem{Text = "What is your favorite spot?"}
                }, "Select a Question")
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.SecretQuestion)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.SecretAnswer)
            </td>
            <td>
                @Html.TextBoxFor(a => a.SecretAnswer)
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.SecretAnswer)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.Status)
            </td>
            <td>
                @Html.DropDownListFor(a => a.Status, new List<SelectListItem> 
                {
                    new SelectListItem{Text="Enable"},
                    new SelectListItem{Text="Disable"}
                },"Select Status")
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.Status)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.Role)
            </td>
            <td>
                @Html.DropDownListFor(a => a.Role, new List<SelectListItem> 
                {
                    new SelectListItem{Text="Administrator"},
                    new SelectListItem{Text="Supervisor"},
                    new SelectListItem{Text="Staff"} 
                },"Select Role")
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.Role)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.CreatedBy)
            </td>
            <td>
                @Html.TextBoxFor(a => a.CreatedBy, new { Value = User.Identity.Name, @readonly = "readonly" })
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.CreatedBy)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a => a.CreatedDate)
            </td>
            <td>
                @Html.TextBoxFor(a => a.CreatedDate, new { Value = @DateTime.Today.Date.ToString("dd-MM-yyyy"), @readonly = "readonly" })
                @*@Html.EditorFor(a => a.CreatedDate)*@
            </td>
            <td>
                @Html.ValidationMessageFor(a => a.CreatedDate)
            </td>
        </tr>
        <tr>
            <td>

            </td>
            <td>
                <input type="submit" value="Register" />
                <input type="reset" value="Reset" />
            </td>
            <td>

            </td>
        </tr>
    </table>
    }    

0 个答案:

没有答案