Hydrogels show potential for microbiologically influenced corrosion protection but face limitations from weak mechanical properties and toxicity from chemical crosslinkers. Herein, we prepared a photocatalytic antibacterial hydrogel by using chitosan and sodium alginate with loaded 2D g-C3N4, showing strong tensile properties, low swelling rates and exceptional antibacterial rate against Escherichia coli and Staphylococcus aureus. The adsorption of bacteria by -NH2 and the generation of reactive oxygen species by 2D g-C3N4 are the main reasons for antibacterial activity. Additionally, the electron-rich microenvironment formed by -NH2 and -OH attracts the h+ generated by 2D g-C3N4 photocatalysis, thereby increasing the charge carrier separation efficiency. Density functional theory calculations also support this inference. The inclusion of 2D g-C3N4 nanomaterials changes the hydrogel structure, disrupting hydrogen bonds to expose more -NH2 groups that bind with H+ to enhance active adsorption. This innovative hydrogel presents a novel approach for safeguarding against microbial corrosion in marine settings.