我在mvc有点新,我不知道我错过了什么。当我启动登录时,在foreach视图中(模型中的var项)< - 模型获取为null,并以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 :(得分: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);
}
}