隐藏在索引上显示Divs导致错误

时间:2014-12-23 18:58:26

标签: asp.net-mvc nullreferenceexception

我是asp.net mvc的新手,我遇到了一些问题。我想要做的是在索引上显示一个div,允许用户输入名称并从下拉列表中选择值。然后在“生成密码”中隐藏初始div并显示div“Hi'UserName'您输入'value1','value2'。最终我想要的是捕获UserName并使用下拉列表中的值创建随机密码(尚未启动该模块“ugh”。它会做什么就是说'HelloName'你的新密码是'密码'。密码将包含他们选择的长度和最大字母数字他们想要。每次我尝试时都会收到以下错误。

System.NullReferenceException was unhandled by user code

在此

 @Html.DropDownListFor(m => m.LenOfPass, Model.Lengths, "Please select...", new { @class = "form-control" })

[基于@ Haney回应的更新代码]

新代码相同的错误;

控制器;

using System;
using PassGen.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;


namespace PassGen.Controllers
{
public class HomeController : Controller
{

    private IEnumerable<int> GetLengths()
    {
        return new List<int>
        {
            8,10,15,20,25
        };
    }

    private IEnumerable<int> GetAlpha()
    {
        return new List<int>
        {
            1,2,3,4,5
        };
    }
    private IEnumerable<SelectListItem> GetLengthList(IEnumerable<int> elements)
    {
        var passLens = new List<SelectListItem>();
        foreach (var len in elements)
        {
            string lengths = Convert.ToString(len);
            passLens.Add(new SelectListItem { Value = lengths, Text = lengths });
        }
        return passLens;
    }
    private IEnumerable<SelectListItem> GetAlphaList(IEnumerable<int> element)
    {
        var alphaMax = new List<SelectListItem>();
        foreach (var alpha in element)
        {
            string alphas = Convert.ToString(alpha);
            alphaMax.Add(new SelectListItem { Value = alphas, Text = alphas });
        }
        return alphaMax;
    }

    [HttpGet]
    public ViewResult Index()
    {
        ViewBag.ShowDetails = false;
        var LenOfPass = GetLengths();
        var MaxOfAlpha = GetAlpha();
        var model = new PassGenerator();

        model.LenOfPass = new List<SelectListItem>(); // Note initialization of the property
        model.Lengths = GetLengthList(LenOfPass);
        model.Alphas = GetAlphaList(MaxOfAlpha);

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(PassGenerator response)
    {
        ViewBag.ShowDetails = false; 
        if (ModelState.IsValid)
        {
            ViewBag.ShowDetails = true;

            ViewBag.UserName = response.UserName;
            ViewBag.PassLength = response.LenOfPass;
            ViewBag.AlphaMax = response.MaxOfAlpha;

            return PartialView ("Index",response);

        }
        else
        {
            //There is a validation error
            return View();
        }

    }
  }
}

模型;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security;
using System.Security.Cryptography;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace PassGen.Models
{
public class PassGenerator
{
    [Required(ErrorMessage = "Please enter your name!")]
    public string UserName { get; set; }

    //This property will hold Length of password chosen by User.
    [Required(ErrorMessage = "Please choose a length for your password!")]
    public int LenOfPass { get; set; }

    //This will hold Lengths for selection
    public IEnumerable<SelectListItem> Lengths { get; set;}

    //This property will hold Maximum number of Alphanumeric characters chosen by User.
    [Required(ErrorMessage = "Please choose the maximum number of alphanumeric characters that you want included!")]
    public int MaxOfAlpha { get; set; }

    //This will hold values for Max Alphanumeric.
    public IEnumerable<SelectListItem> Alphas { get; set;}

    //This property will hold the Random Password that is generated
    public string RandPass { get; set;}

  }
}

索引没有改变,请原谅我是新手。 指数:

@model PassGen.Models.PassGenerator

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<div class="inital-form">
    @using (Html.BeginForm()) { 
        @Html.ValidationSummary()
        <p>Your Name: @Html.TextBoxFor(x => x.UserName)</p>
        <p>Please choose the length of your password:
            @Html.DropDownListFor(m => m.LenOfPass, Model.Lengths, "Please select...", new { @class = "form-control" })
        </p>
        <p>Please choose the Maximum number of Alphanumeric characters you would like included:
            @Html.DropDownListFor(m => m.MaxOfAlpha, Model.Alphas, "Please select...", new { @class = "form-control" }) 
        </p>
        <input type="submit" value="Generate Your Password" />
    }
</div>
@if (ViewBag.ShowDetails) { 
<div class="response-section">
    <h1>Hello @Html.DisplayFor(m => m.UserName)</h1>
    <p>You have entered the following information;</p>
    <ul>
        <li>Your requested length for your password: @Html.DisplayFor(m => m.LenOfPass)</li>
        <li>Maximum number of Alphanumeric Characters required: @Html.DisplayFor(m => m.MaxOfAlpha)</li>
    </ul>
</div>
}
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您永远不会在LenOfPass个实例上初始化属性PassGenerator,因此它仍为null。然后,在视图中引用它时,会抛出NullReferenceException。替代您的控制器:

public ViewResult Index()
{
    ViewBag.ShowDetails = false;
    var LenOfPass = GetLengths();
    var MaxOfAlpha = GetAlpha();
    var model = new PassGenerator();
    model.LenOfPass = new List<SelectListItem>(); // Note initialization of the property

    model.Lengths = GetLengthList(LenOfPass);
    model.Alphas = GetAlphaList(MaxOfAlpha);


    return View(model);
}

在大多数编程语言和C#中,尝试引用null变量,字段或属性会导致NullReferenceException

另外值得注意的是:通常,选择列表将产生单个值。 LenOfPass因此应为IEnumerable<SelectListItem>,而是stringint或您期望将值设置为的任何类型。

public int LenOfPass { get; set; }

这不会导致异常,因为intstruct AKA值类型,不能是null