gpt4 book ai didi

c# - 编辑时禁用用户名验证

转载 作者:太空宇宙 更新时间:2023-11-03 21:53:51 24 4
gpt4 key购买 nike

我为唯一用户名创建了验证,现在我无法编辑我的用户。它说用户名已被占用,这是有道理的,因为它已被我尝试编辑的用户占用。我什至不想编辑用户名,但由于这个错误,我也无法编辑任何其他字段。

如何为我的 EDIT 操作禁用唯一用户名验证?

验证者

public override bool IsValid(object value)
{
if (value == null) return false;
FinanceDataContext _db = new FinanceDataContext();
var user = _db.Users.ToList().Where(x => x.Username.ToLower() == value.ToString().ToLower()).SingleOrDefault();
if (user == null) return true;
return false;
}

Action

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(User u)
{
// Get user we want to edit
var user = _db.Users.Where(x => x.ID == u.ID).SingleOrDefault();
if (user == null) return HttpNotFound();

// Set values and save changes
user.Address = u.Address;
if (!string.IsNullOrEmpty(u.Password)) user.Password = Infrastructure.Encryption.SHA256(u.Password);
_db.SaveChanges(); // validation error

return null;
}

模型

public class User
{
public int ID { get; set; }

[Required]
[UniqueUsername(ErrorMessage = "Username is already taken")]
public string Username { get; set; }

[Required]
public string Password { get; set; }

public string Address { get; set; }
}

错误

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

最佳答案

在 UniqueUsername 属性的“AdditionalFields”参数中传递“ID”属性,所以我猜你的代码应该是这样的

类属性:

[Required]
[UniqueUsername(ErrorMessage = "Username is already taken", AdditionalFields = "ID")]
public string Username { get; set; }

验证操作:

public ActionResult UniqueUsername(string userName, int id)
{
FinanceDataContext _db = new FinanceDataContext();
var user = _db.Users.ToList().SingleOrDefault(x => x.Username.ToLower() == value.ToString().ToLower() && x.ID != id);
return Json(user == null, JsonRequestBehavior.AllowGet);
}

希望这会有所帮助!!

关于c# - 编辑时禁用用户名验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13182421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com