我有我不能修復這個基本的錯誤...對象引用不設置到對象基本誤差System.NullReferenceException
我使用asp.net mvc4與EF的實例
我控制器
public class PostController : Controller
{
private UsersContext db = new UsersContext();
public ActionResult Index()
{
return View(db.Posts.ToList());
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(FormCollection values)
{
var post = new Post();
TryUpdateModel(post);
if(ModelState.IsValid)
{
var context = new UsersContext();
var username = User.Identity.Name;
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
var userid = user.UserId;
// var firstname = user.FirstName;
post.UserId = userid;
post.Date = DateTime.Now;
db.Posts.Add(post);
db.SaveChanges();
}
return View("Index");
}
和我的觀點:
@model IEnumerable<MyProject.Models.Post>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Content)
</th>
<th>
@Html.DisplayNameFor(model => model.Date)
</th>
<th></th>
</tr>
@foreach (var item in Model) { //**line with error**
<tr>
<td>
@Html.DisplayFor(modelItem => item.Content)
</td>
<td>
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.PostId }) |
@Html.ActionLink("Details", "Details", new { id=item.PostId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.PostId })
</td>
</tr>
}
</table>
感謝您的幫助
你在哪一點得到錯誤? –