The binding of hydrated Mg2+ and Ca2+ ions with a DNA fragment containing two phosphate groups, three sugar units, and a G.C base pair is modeled in the anion and dianion states using a three-layer ONIOM approach. A monodentate binding mode was the most stable structure observed for both the ions in the anion model. However, the interactions of Mg2+ and Ca2+ with the dianion model of the DNA fragment gave rise to a large structural deformation at the base pair region, leading to the formation of "ring" structures. In both anion and dianion models, Mg2+-bound structures were considerably more stable than the corresponding Ca2+-bound structures. This feature and the formation of ring structures in the dianion models strongly supported the higher coordination power of the Mg2+ toward DNA systems for its compaction. The charge of the DNA fragment appeared to be crucial in deciding the binding strength as well as the binding mechanism of the metal ions. To the best of our knowledge, this is the first theoretical investigation of the interaction of a comparatively larger DNA model system with the biologically important Mg2+ and Ca2+ ions.