我正在使用此网站,我在将复选框设置为数据库以设置true或false时将我的IsActive
值设置为true或false以使用代码更新帐户时遇到困难关于MVC的第一种方法。
在我的帐户和身份模型上
公共类RegisterViewModel { public bool IsActive {get;组; } }
和我的帐户控制器
//
// GET: /Account/Update
[HttpGet]
[ETAuthorizeAttribute]
public ActionResult Update(string email)
{
var user = _db.Users.FirstOrDefault(x => x.Email == email);
ViewBag.IsActive = user.IsActive;
ViewBag.CostCentres = new SelectList(_db.CostCentres.Select(x => x.Station).Distinct());
ViewBag.Hotel = new SelectList(_db.Hotels.Where(x => x.IsBlocked == true).Distinct(), "HotelId", "HotelName");
string selected = "";
foreach (var item in user.Roles)
selected += item.RoleId + ",";
ViewBag.Selected = selected;
ViewBag.Roles = _db.Roles.ToList();
RegisterViewModel model = new RegisterViewModel();
model.Email = user.Email;
return View(model);
}
//
// POST: /Account/Register
[HttpPost]
[ETAuthorizeAttribute]
[ValidateAntiForgeryToken]
public ActionResult Update(RegisterViewModel model)
{
bool isActive = Convert.ToBoolean(Request.Form["active"]);
string role = Request.Form["role"];
if (role != null)
{
ApplicationUser user = _db.Users.FirstOrDefault(x => x.Email == model.Email);
if (user != null)
{
user.HotelId = model.HotelId;
user.Station = model.Station;
user.FullName = model.FullName;
user.IsActive = isActive;
try {
_db.Entry(user).State = EntityState.Modified;
_db.SaveChanges();
}
// return RedirectToAction("Index");
catch(Exception e)
{
_db.ClearUserRoles(UserManager, user.Id);
string[] roles = role.Split(',');
foreach (var item in roles)
{
string name = _db.Roles.FirstOrDefault(x => x.Id == item).Name;
_db.AddUserToRole(UserManager, user.Id, name);
}
return RedirectToAction("Index", "Account");
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
并且在我看来......
<div class="form-group">
@Html.Label("IsActive", new { @class = "control-labelcol-md-2" })
<div class="col-md-10">
<div class="checkbox col-md-3">
@if (ViewBag.IsActive)
{
<input type="checkbox" name="active" value="@ViewBag.IsActive" checked/>}
else
{
<input type="checkbox" name="active" value="@ViewBag.IsActive" /> }
</div>
</div>
</div>
答案 0 :(得分:2)
基本上,您必须将HTML控件的名称与控制器示例中的变量相同:
public ActionResult Index(bool checkboxControl)
{
return View();
}
在HTML端,代码必须是
<input type="checkbox" name="checkboxControl" />
如果您首先使用代码优先方法或数据库,这无关紧要,这是MVC工作的基本方法
答案 1 :(得分:0)
您没有在模型中传递复选框的值
<div class="form-group">
@Html.Label("IsActive", new { @class = "control-labelcol-md-2" })
<div class="col-md-10">
<div class="checkbox col-md-3">
@if (ViewBag.IsActive)
{
<input type="checkbox" name="active" value="@ViewBag.IsActive" checked/>
} else
{
<input type="checkbox" name="active" value="@ViewBag.IsActive" /> }
</div>
</div>
</div>
将此更改为
<div class="form-group">
@Html.Label("IsActive", new { @class = "control-labelcol-md-2})
<div class="col-md-10">
<div class="checkbox col-md-3">
@Html.CheckBoxFor(m => m.IsActive, new { id = "YourId"})
</div>
</div>
</div>
您需要检查视图,它将根据您从服务器端传递的值工作..
希望它对你有用..