Click here to Skip to main content
15,898,949 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Caution When You Are Disabling a Checkbox in Edit View

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
1 Feb 2014CPOL 7K   1  
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.

C#
[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:

C#
if(@ViewBag["Disable"] == true)
	{ 
		@Html.CheckBoxFor(model => model.Isactive , new { @disabled = "disabled" })  
	} 
	else  
	{ 
		@Html.CheckBoxFor(model => model.Isactive )  
	} 

My addition is as follows:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --