编辑方法 asp.net



我正在尝试为用户可以编辑用户名和电子邮件的用户创建一个编辑页面。 我的控制器如下所示:

public ActionResult Edit(string Name="0")
{
using (var applicationContext = new ApplicationContext())
{
var User = applicationContext.ApplicationUsers.Where(s => s.Name == Name).SingleOrDefault();
if (User == null)
{
return NotFound();
}
return View(User);
}
}

[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditPost(ApplicationUser user)
{
if (Name == null)
{
return NotFound();
}
using (var applicationContext = new ApplicationContext())
{
var UserUpdate = await applicationContext.ApplicationUsers.SingleOrDefaultAsync(s => s.Name == Name);
if (await TryUpdateModelAsync<ApplicationUser>(UserUpdate, "", s => s.Name, s => s.Email))
{
try
{
await applicationContext.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +"Try again, and if the problem persists, " +"see your system administrator.");
}
}
return View(UserUpdate);
}
}

这也是我的模型:

public class ApplicationUser : BaseEntity
{
public string Name { get; set; }
public string DirectoryId { get; set; }
public string Domain { get; set; }
public bool IsActive { get; set; }
public List<ApplicationUser> AllUsers { get; set; }
public ApplicationUser()
{
AllUsers = new List<ApplicationUser>();
}
}

有人可以帮助我我不明白这里出了什么问题,我在编辑时遇到了问题,因为我总是使用 Int Id 而不是字符串 ID 进行编辑。 这对我来说很奇怪,有人可以帮助我吗?

正如我在评论中所说,在ActionResult Edit(string Name="0")中,给出主键的正确名称,然后按该名称过滤/获取对象,例如:(var UserUpdate = await applicationContext.ApplicationUsers.SingleOrDefaultAsync(s => s.PrimaryKeyPropertyName == user.PrimaryKeyPropertyName);)

如果您收到一个对象ApplicationUser,并且假设该对象是视图的模型,并且您有一个属性Id,它将如下所示:

public ActionResult Edit(int Id)
{
using (var applicationContext = new ApplicationContext())
{
var User = applicationContext.ApplicationUsers.Where(s => s.Id ==  Id).SingleOrDefault();
if (User == null)
{
return NotFound();
}
return View(User);
}
}

[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditPost(ApplicationUser user)
{
//Here will return every time NotFound/error, right? Where you defined Name?!
/*if (Name == null)
{
return NotFound();
}*/
using (var applicationContext = new ApplicationContext())
{
var UserUpdate = await applicationContext.ApplicationUsers.SingleOrDefaultAsync(s => s.Id == user.Id);
...

最新更新