In this paper, by combination of the specificity of a molecularly imprinted technique, the water solubility of hydrogels and the photoisomerization property of azobenzene chromophores, we report a new and quick detection method for trace melamine in aqueous media based on photo-responsive molecularly imprinted hydrogels (MIHs). The MIHs were fabricated using a water-soluble azobenzene-containing 4-[(4-methacryloyloxy)phenylazo]benzenesulfonic acid (MAPASA) as the functional monomer, 1,3,5-benzenetriol as a mimic template, and tetramethacryloyl triethylene tetramine (TTT) as the cross-linker. The MIHs show specific affinity to melamine with a binding constant of 3.20 × 10 ⁴ M⁻¹ in aqueous Tris–HCl buffer at pH 7.0. The density of the melamine-specific receptor sites in the MIHs material is 2.69 μmol g⁻¹ MIHs. Upon alternate irradiation at 365 and 440 nm, the MIHs can quantitatively uptake and release melamine. The photoisomerization rate of MIHs is related to the concentration of melamine in the detecting solution, and therefore, a quick detection method for trace melamine is established. Analytical application of the MIHs to detect the melamine concentration in both milk and milk powder has been accomplished successfully with a simple pre-treatment of the samples. Copyright © 2012 The Royal Society of Chemistry.