我在這個網站上工作,我很難設置從我的複選框到數據庫的真或假,以將我的IsActive
值設置爲true或false,以便更新使用代碼的帳戶在MVC上的方法。無法轉換爲布爾
我的帳戶和身份識別模型
公共類RegisterViewModel { 公共布爾IsActive {獲得;組; }}
和我的帳戶控制器
//
// 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>
你可以請張貼你的代碼..你已經嘗試過! –
分享你到目前爲止所做的一切。也請看[在ASP.NET MVC 4中獲取複選框值](http://stackoverflow.com/questions/14730746/getting-checkbox-value-in-asp-net-mvc-4)和[mvc3複選框值在提交後](http://stackoverflow.com/questions/17868236/mvc3-checkbox-value-after-submit) –
只是做了以上 – ILoveCode