I am still new to MVC, and I am trying to figure out how to create functions that get generated inside of the .cshtml file and move them out to a central location so that they can be reused.
For example, using the DevExpress libraries to create grids and popups. This is a column definition for a grid:
settings.Columns.Add( column => {
column.ColumnType = MVCxGridViewColumnType.TextBox;
column.Caption = "Samples";
column.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
column.CellStyle.HorizontalAlign = HorizontalAlign.Center;
column.SetDataItemTemplateContent( Content => ViewContext.Writer.Write(
GeneratePopup( "Samples"
, DataBinder.Eval( Content.DataItem , "SampleHTML" ).ToString()
, "Samp" + DataBinder.Eval( Content.DataItem , "Row" ).ToString()
, (bool)DataBinder.Eval( Content.DataItem , "ShowSample" ) , 750 , (string)DataBinder.Eval( Content.DataItem , "SampleCount" ) )
) );
} );
In it it makes a call to "GeneratePopup", which is defined in the .cshtml file as:
@functions {
private string GeneratePopup(string aTitle , string aString , string aID , bool aShow , int aWidth , string aSuffix ) {
Works great. Except, there is a bunch of functionality in it that I want to reuse in other forms, I don't want to copy GeneratePopup all over the place.
How do I create a central reusable version of GeneratePopup?
You should move the helper to a separate CSHTML file in the App_Code
directory.
You can then call it as a static method from any view.
See this blog post, and my in-depth explanation.