【问题标题】:System.NullReferenceException when trying to iterate list in view尝试在视图中迭代列表时出现 System.NullReferenceException
【发布时间】:2016-03-29 04:32:02
【问题描述】:

我在 mvc 有点新,我不知道我想念什么。当我启动登录时,在 foreach(模型中的变量项)的视图中

型号:

    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>
       }
    }

【问题讨论】:

    标签: asp.net-mvc view


    【解决方案1】:

    当您在控制器操作中渲染此视图时,您似乎忘记将 List&lt;TheOnlineArchivator.Models.LoginModels&gt; 的实例传递给视图。到目前为止,您展示的是您的 Login 控制器操作,但您没有向我们展示您的 Home/Index 操作。在此操作中,您应该确保将非空模型传递给视图:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多