I have this basic error that i can’t fix… Object reference not set to an instance of an object
I’m using asp.net mvc4 with ef
My controller
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");
}
and my view :
@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>
Thanks for your help
You forgot to send a model to the view after the GET action in your controller. Your
returnstatement should probably be:You have to supply something for the model or it will be
nullin the view.You’ll probably have the same problem with your POST method as well, which returns:
Rather than doing that, you should probably just redirect to the Index action:
Also, you would only want to do that on success – if the model state wasn’t valid, you probably want to go back to the create screen to show the errors. So your post action would end up something like this: