简体   繁体   中英

Get a user Asp .net MVC C#

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?

You can write following way :

public ActionResult Edit(string id) {

  ApplicationDbContext db = new ApplicationDbContext();
  ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == id);
  return View(user);
}

You can find the user with:

db.Users.FirstOrDefault(u => u.Id.Equals(id))

and if it returns null maybe you do not have such a user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM