2016-03-28 8 views
0

mvcで少し新しいですが、私は何が見つからないのか分かりません。私がログインを起動すると、foreach(Model内のvarアイテム)のビュー< - モデルはnullになり、System.NullReferenceExceptionで停止します。私は本当に理由を知りませんし、次のコードが間違っているか、どこでエラーを探し始めるべきか、誰かが助言してくれることを願っています。System.NullReferenceExceptionビューを反復しようとしたとき

モデル:

public class LoginModels 
    { 
     public string UserLogin { get; set; } 
     public string Address { get; set; } 
     public string Password { get; set; } 
     public List<string> emailSubject { get; set; } 
    } 

コントローラ:

public ActionResult Login(string address, string password, LoginModels model) 
    { 
     using (Imap imap = new Imap()) 
     { 
      try 
      { 
       imap.ConnectSSL("imap.gmail.com"); 
       imap.Login(address, password); 
       imap.SelectInbox(); 
       List<long> uids = imap.Search(Flag.All); 

       model.emailSubject = new List<string>();     
       foreach (long uid in uids) 
       { 
        var eml = imap.GetMessageByUID(uid); 
        IMail email = new MailBuilder().CreateFromEml(eml); 

        model.emailSubject.Add(email.Subject); 
       } 

       Session["user"] = new LoginModels() { UserLogin = address, Address = address }; 
       return RedirectToAction("Index", "Home", model.emailSubject); 
      } 
      catch (Exception e) 
      { 
       ViewBag.exceptionMessage = e; 
       return View("LoginFailed"); 
      } 
     } 

ビュー:

@using TheOnlineArchivator.Models; 
    @model List<TheOnlineArchivator.Models.LoginModels> 
    @{ 
     ViewBag.Title = "Home"; 
    } 
    @{ 
     var user = Session["user"] as LoginModels; 
     if (user != null) 
     { 
      <h2>You are logged on as @user.Address</h2> 
      <table> 
      @foreach (var item in Model) 
      { 
       foreach (var elem in item.emailSubject) 
       { 
        <tr> 
        <td>@elem</td> 
        </tr> 
       } 
      } 
      </table> 
     } 
    } 

答えて

0

それはあなたがしたときのビューにList<TheOnlineArchivator.Models.LoginModels>のインスタンスを渡すのを忘れように見えますあなたのコントローラーアクション内でこのビューをレンダリングしました。あなたがこれまで示してきたのは、あなたのログインコントローラのアクションですが、私たちにあなたのホーム/インデックスアクションを表示していませんでした。このアクションの中で、ヌル以外のモデルをビューに渡していることを確認する必要があります。

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     List<LoginModels> model = ... go get your model from somewhere and make sure it is not null 
     return View(model); 
    } 
}