尝试验证并在控制器中手动设置值 (ASP MVC 3)
我有一个供管理员和普通用户使用的“新用户”表单。两种形式都使用 RegisterModel
public class RegisterModel
{
[Required]
public string Name { get; set; }
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
区别在于,在我的前端“新用户”页面上,我希望用户提供自己的密码。但在后端,我希望系统生成密码。
由于我对两种表单使用相同的 RegisterModel
,因此我在后端收到验证错误,提示 Password is required.
。
我想,我可以通过将其添加到我的控制器来解决这个问题:
[HttpPost]
public ActionResult New(RegisterModel model)
{
model.Password = Membership.GeneratePassword(6, 1);
if (TryValidateModel(model))
{
// Do stuff
}
return View(model);
}
但我仍然收到错误消息需要密码。
。当我在控制器中调用 TryValidate
时,为什么会出现此问题?
对于此问题,最佳实践是什么?创建一个单独的 RegisterModelBackEnd 或是否有其他解决方案?
I have a "New user" form both for admins and for regular users. Both form use the RegisterModel
public class RegisterModel
{
[Required]
public string Name { get; set; }
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
The difference is that on my front end "New user" page I want users to provide their own password. But in back end, I want the system to generate the password.
Since I use the same RegisterModel
for both forms, I get a validateion error in the back end saying Password is required.
.
I thought, I could solve this by adding this to my controller:
[HttpPost]
public ActionResult New(RegisterModel model)
{
model.Password = Membership.GeneratePassword(6, 1);
if (TryValidateModel(model))
{
// Do stuff
}
return View(model);
}
But I still get the error message Password is required.
. Why is this the issue when I do call TryValidate
in my controller?
What would be best practice for this issue, create a separate RegisterModelBackEnd
or are there any other solutions to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
手动更新模型时,不需要将其用作Action中的参数。另外,使用此重载,它允许您仅指定绑定的属性会发生。
因此,工作代码将是
您可以使用 BindAttribute
最后是最简单且最好的方法
When updating model manually, you do not need to use it as parameter in Action. Also, use this overload that lets you specify only the properties on which binding will occur.
So, the working code will be
You can make this even simpler, using BindAttribute
And finally simplest and the best way