Variational stabilization of the ionic charge densities in the electron-gas theory of crystals: Applications to MgO and CaO