Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Caution When You Are Disabling a Checkbox in Edit View

0.00/5 (No votes)
1 Feb 2014 2  
Caution when you are disabling a checkbox in Edit View

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 )  
	}  

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here