I am trying to get an Application User by its Id but it is always returning null. I need it to chow its details on the edit view but because it is null, my edit view has all fields empty.
This is my controller:
public ActionResult Edit(string id) {
ApplicationDbContext db = new ApplicationDbContext();
ApplicationUser user = db.Users.Find(id);
return View(user);
}
[HttpPost]
public ActionResult Edit(ApplicationUser user) {
if (ModelState.IsValid) {
ApplicationDbContext db = new ApplicationDbContext();
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
return View(user);
}
The problem is that the "db.Users.Find(id);" is returning null. Instead of that If I do the following code everything works:
public ActionResult Edit(string id) {
ApplicationDbContext db = new ApplicationDbContext();
ApplicationUser user = new ApplicationUser();
user.Email = "test@gmail.com";
//(...)
return View(user);
}
Can you give me an idea of what can be wrong with this?
Thanks in advance for any help.
Update: Thanks for all your comments. As some of you pointed out the reason is actually very simple - I am searching for id's that don't exist on the DB. However I don't know how it is happening. When I show my ids on a table (check code below), the ids are different from the ones I can see on my table on SQL Object Explorer. How can that happen? Every other information (name and email) is right.
@model IEnumerable<FMS.Models.ApplicationUser>
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>Name</th>
<th>E-mail</th>
<th>ID</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model) {
<tr>
<td>@user.Name</td>
<td>@user.Email</td>
<td>@user.Id</td>
<td class="pull-right">
@Html.ActionLink("Edit", "Edit", new { id = user.Id})
</td>
</tr>
}
</tbody>
</table>
Update 2: I just noticed that every time I refresh the view, the id's on the ID column are different! What can be causing this?