Introduction
While reviewing code of another developer for some functionality, a checkbox disabled in edit mode and when user saves the data in edit mode, Active checkbox becomes inactive.
Background
A bug was raised by the team in a master when 1 record is marked as active and used in transactions then there was a requirement that user cannot deactivate the record. For such functionality, the developer checked some conditions in Edit HTTpGEt
and stored data in a viewbag in edit view. He checked that if viewbag
is not null
, then disable the checkbox
else don't disable checkbox
. I will show in code what was wrong.
Using the Code
Controller Code
Here is a simple scenario.
There is 1 master called as address master. If the address is used in student master, then user cannot deactivate the same address in address master.
Repository pattern is used here.
[HttpGet]
public ActionResult Edit(int id)
{
var address = _repositoryFactory.AddresRepository.Findsingle(a => a.ID == id) ;
var studentExists = _repositoryFactory.StudentRepository.Find(a => a.addressID == address.ID )
if(studentExists.Any())
{
ViewBag["Disable"] == true;
}
else
{
ViewBag["Disable"] == false;
}
return View(address);
}
View Code
The old code is given below:
if(@ViewBag["Disable"] == true)
{
@Html.CheckBoxFor(model => model.Isactive , new { @disabled = "disabled" })
}
else
{
@Html.CheckBoxFor(model => model.Isactive )
}
My addition is as follows:
if(@ViewBag["Disable"] == true)
{
@Html.Hiddenfor(model => model.Isactive)
@Html.CheckBoxFor(model => model.Isactive , new { @disabled = "disabled" })
}
else
{
@Html.CheckBoxFor(model => model.Isactive )
}