【发布时间】:2019-03-23 12:52:39
【问题描述】:
我在一个创建 2 类用户的项目中工作:管理员和成员。为了区分它们,我设置了一个 bool 值,true => admin || false => 成员。
只有管理员可以创建管理员,如果匿名用户尝试创建帐户,则该字段的默认值需要为 false。我在该字段中设置了一个 @html.HiddenFor,但它发送了一个空值,因此模型无法保存在数据库中。
这是代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Registro(
[Bind(Include="Id,Login,Pass,Nombre,Apellido,Rol")]Usuario objUser)
{
//somecode
var errors = ModelState.Values.SelectMany(v => v.Errors);
//error shows the null 'rol' parameter
if (ModelState.IsValid)
{
db.Usuario.Add(objUser);
db.SaveChanges();
return RedirectToAction("Login");
}
return View(objUser);
}
剃须刀:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Rol)
//some inputs for the other fields
}
没有找到相关的信息 有可能还是我需要做其他事情?
【问题讨论】:
-
您可以在 GET 操作中设置
Rol属性值。但请记住,永远不要相信来自客户端的数据。 -
就像
public ActionResult Reg(){ objuser.Rol=false; return View(objUser); }我不太习惯使用mvc。 -
那么你这样做有什么问题?
-
@Yantup 你是什么 db.Usuario.rol 的数据类型?它不能为空吗?是否分配了任何默认值?
标签: c# html asp.net-mvc razor frameworks