2014-12-23 41 views
1

我是新來的asp.net mvc和我有一些問題。我想要做的是在索引上顯示div,以便用戶輸入名稱並從下拉列表中選擇值。然後在「生成密碼」上隱藏起始div並顯示div「Hi'UserName''你輸入了'value1','value2'。最終我想要的是捕獲UserName並使用下拉列表中的值創建一個隨機密碼(還沒有啓動該模塊,但「呃」,它會做的是說你好'用戶名'你的新密碼是'密碼',密碼將包含他們選擇的長度和最大數量的字母字符他們想要的。每次我嘗試我碰到下面的錯誤。隱藏在索引導致錯誤顯示科

System.NullReferenceException was unhandled by user code 

這個

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

[更新的代碼基於@哈尼的迴應]

新代碼相同的錯誤;

控制器;

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(); 
     } 

    } 
    } 
} 

Model;

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> 
+0

您還有這個:model.LenOfPass = new List ()。你的模型的這個屬性是一個int,而不是List 。 –

+0

@MattyM我還是不明白。你是說我應該將模型代碼更改爲public List LenOfPass {get;組; }?我試過了,現在我明白了。 App_Web_ncrwhue0.dll中發生類型'System.NullReferenceException'的異常,但未在用戶代碼中處理 附加信息:未將對象引用設置爲對象的實例。 – daspixl

+0

幾乎所有的'NullReferenceException'都是一樣的。請參閱「[什麼是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)」的一些提示。 –

回答

1

你永遠不會在你的PassGenerator實例初始化屬性LenOfPass,所以它仍然null。然後,在View中引用它時,會引發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>而不是string,int或您希望設置的值。因爲intstruct AKA值類型和不能null

public int LenOfPass { get; set; } 

這不會引起一個異常。

+0

LenOfPass不需要是一個單一的值(int),而不是一個List ,因爲我認爲你會想要這個綁定到從model.Lengths的選項列表中選擇的單個值? –

+0

@MattyM是啊,我最初寫我的答案後不久才意識到。請看我更新的答案。 – Haney

+0

如果我嘗試你的代碼@Haney,我得到以下錯誤。錯誤不能隱式地將類型'System.Collections.Generic.List '轉換爲'int' – daspixl