我有这个基本错误,我无法解决...对象引用未设置为对象的实例
我正在使用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>
感谢您的帮助
答案 0 :(得分:8)
在控制器中执行GET操作后,您忘记将模型发送到视图。您的return
声明应该是:
public ActionResult Create()
{
return View("Create", new Post());
}
您必须为模型提供内容,或者在视图中为null
。
你的POST方法也可能遇到同样的问题,它会返回:
return View("Index");
您可能只需重定向到Index操作,而不是这样做:
return RedirectToAction("Index");
此外,您只想在成功时这样做 - 如果模型状态无效,您可能需要返回创建屏幕以显示错误。所以你的帖子行动最终会是这样的:
[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 RedirectToAction("Index");
}
return View("Create", post);
}
答案 1 :(得分:0)
Object reference not set to an instance of an object
表示您正在尝试访问null
对象的属性或方法。