-1

我是ASP.NET MVC的新手。我正在使用個人用戶帳戶的示例項目。我在我的項目文件夾中創建了一個新區域,它包含UserManagement文件夾。它包含一個名爲UserManagementMethods.cs文件已下面的代碼:NullReferenceException發生在DropDownListFor,ASP.NET MVC

namespace Library.Areas.UserManagement 
{ 
    public class UserManagementMethods 
    { 
      public IEnumerable<string> GetGenderList() 
      { 
      List<string> GenderGroup = new List<string> 
                 { 
                  "Male", 
                  "Female", 
                  "Not in the Above", 
                 }; 
      return GenderGroup; 

      } 

      public IEnumerable<SelectListItem> GetSelectedGenderItem(IEnumerable<string> elements) 
      { 

       foreach (var element in elements) 
       { 
        selectList.Add(new SelectListItem 
        { 
         Value = element, 
         Text = element 
        }); 
       } 

       return selectList; 
      } 

    } 
} 

在的AccountController,我創建了一個UserManagementMethods對象,userManagement:

在註冊
using Library.Areas.UserManagement; 
........ 
........ 
UserManagementMethods userManagement = new UserManagementMethods(); 

然後()中的AccountController,我所謂UserManagementMethods方法

var genderList = userManagement.GetGenderList(); 
var model = new RegisterViewModel(); 
model.GenderList = userManagement.GetSelectedGenderItem(genderList); 
return View(); 

我Register.cshtml

創建一個DropDownList 10
<div class="form-group"> 
    @Html.LabelFor(m => m.Gender, new { @class = "col-md-4 control-label" }) 
    <div class="col-md-8"> 
     @Html.DropDownListFor(m => m.Gender, Model.GenderList, "Select An Option", new { @class = "form-control" }) 
    </div> 
</div> 

當我運行該項目,並導航到/Account/Register的NullReferenceException附近發生DropDownListFor場。

/Account/Register

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 49: @Html.LabelFor(m => m.Gender, new { @class= "col-md-4 control-label"})< 
Line 50: <div class="col-md-8"> 
Line 51:  @Html.DropDownListFor(m => m.Gender, Model.GenderList, "Select An Option", new { @class = "form-control" }) 
Line 52: </div> 
Line 53:</div> 
+0

因爲你不模型返回視圖,以便在考慮到其'null' - '返回查看(模型); –

+0

非常感謝。 – PROTOCOL

回答

0

你是不是送模型視圖。

return View(); 

應該

return View(model); 
+0

非常感謝。 – PROTOCOL