SharePoint 2013 custom master page with code behind

Sometime we need to set control value dynamically on our custom master page in SharePoint. The one way is to write custom JavaScript code using Client Side Object Model (CSOM) and we can add that JavaScript on master page.  The other way to create custom class file and attach that file with master page.

Follow below steps to create master page with code behind in SharePoint Project.

1) Create module file in SharePoint solution. I have given module name as CustomMasterPage.


2) Rename the sample.txt with “MyCustomMaster.master”. Add your master page content in “MyCustomMaster.master” file.

3) Now click on module(CustomMasterPage) and add new class file. My class file name is “CustomCode.cs”


4)Inherit that class from publishingpagelayout class.

public partial class CustomCode : PublishingLayoutPage
protected void Page_Load(object sender, EventArgs e)

protected void btnHomePageOk_Click(object sender, EventArgs e)


5)Open the master page and add following line at the top.
<%@Master language=”C#” Inherits=”TestProject.Branding.MasterPages.CustomMasterPage.MyCustom,TestProject, Version=, Culture=neutral, PublicKeyToken=ca7bafa503889ee6″ %>

In above line give change namespace as per your need with master page reference, change assembly name as per your need and give public key token.