Click here to Skip to main content
11,706,979 members (47,300 online)
Click here to Skip to main content

Caution When You Are Disabling a Checkbox in Edit View

, 1 Feb 2014 CPOL 3.2K 1
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150819.1 | Last Updated 1 Feb 2014
Article Copyright 2014 by Madhav Hatwalne
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid