0% found this document useful (0 votes)
8 views5 pages

17

The document outlines a C# class named DynamicFormService that connects to a SQL database to fetch form details and generate a Razor page dynamically. It includes methods to retrieve form data using a stored procedure, construct HTML form elements based on the data, and save the generated Razor page to a specified file path. Additionally, it contains a helper method to fetch dropdown values from a lookup table in the database.

Uploaded by

Binu Gibson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

17

The document outlines a C# class named DynamicFormService that connects to a SQL database to fetch form details and generate a Razor page dynamically. It includes methods to retrieve form data using a stored procedure, construct HTML form elements based on the data, and save the generated Razor page to a specified file path. Additionally, it contains a helper method to fetch dropdown values from a lookup table in the database.

Uploaded by

Binu Gibson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

using System.

Data;
using System.Text;
using System;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace TURN.Services
{
public class DynamicFormService
{
private readonly string _connectionString;

public DynamicFormService(string connectionString)


{
_connectionString = connectionString;
}

public DataSet FetchFormDetails(int formCode)


{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("usp_GetFormDetails", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FormCode", formCode);

SqlDataAdapter adapter = new SqlDataAdapter(cmd);


DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
}
}

public void GenerateRazorPage(DataSet ds, string filePath)


{
// Extract necessary tables from dataset
DataTable tblControls = ds.Tables[0]; // tbl_controls
DataTable tblFields = ds.Tables[6]; // tbl_fields
DataTable tblForms = ds.Tables[2]; // tbl_forms
DataTable tblControlSettings = ds.Tables[1]; // Tbl_Controls_Settings

// Extract form title


string formCaption = "Dynamic Form";
if (tblForms.Rows.Count > 0 &&
tblForms.Columns.Contains("Frm_Caption"))
{
formCaption = tblForms.Rows[0]["Frm_Caption"].ToString();
}

// Start Razor Page content with a boxed layout


StringBuilder razorPageContent = new StringBuilder();
razorPageContent.AppendLine($"@page");
razorPageContent.AppendLine($"@{{ ViewData[\"Title\"]
= \"{formCaption}\"; }}");

// Outer Boxed Container


razorPageContent.AppendLine(@"
<div class=""container mt-4"">
<div class=""card shadow-sm border-0"">
<div class=""card-header bg-primary text-white"">
<h3 class=""mb-0"">" + formCaption + @"</h3>
</div>
<div class=""card-body"">
<form method=""post"">");

// Add controls dynamically


foreach (DataRow row in tblControls.Rows)
{
int formCode = Convert.ToInt32(row["Ctrl_Frm_Code"]);
int controlCode = Convert.ToInt32(row["Ctrl_Code"]);
string fieldLabel = row["Ctrl_Caption"].ToString();
string controlType = row["Ctrl_Type"].ToString();

// Construct IDs based on format


string fieldId = $"WEB_{formCode}_0_0_{controlCode}_D";
string textBoxId = $"{fieldId}_TXT";
string labelId = $"{fieldId}_LBL";

// Fetch height and width from Tbl_Controls_Settings


DataRow[] settingRows = tblControlSettings.Select($"Ctrl_Frm_Code =
{formCode} AND Ctrl_Code = {controlCode}");
string height = settingRows.Length > 0 ? settingRows[0]
["Ctrl_Height"].ToString() : "40px";
string width = settingRows.Length > 0 ? settingRows[0]
["Ctrl_Width"].ToString() : "100%";

// Open a new div with two sections (label and control)


razorPageContent.AppendLine($@"<div class=""row mb-3 align-items-
center"">");

// Add Label for all except "VAR" (hidden) and "IMG" (image button)
if (controlType != "VAR" && controlType != "IMG")
{
razorPageContent.AppendLine($@"
<div class=""col-md-4 text-start py-2"" style=""background-color:
#f5f5f5; border-right: 2px solid #ddd; font-weight: bold;"">
<label id=""{labelId}"" for=""{labelId}"" class=""form-
label"">{fieldLabel}</label>
</div>");
}

// Input Section
razorPageContent.AppendLine($@"<div class=""col-md-8"">");

// Control Type Conditions


switch (controlType)
{
case "TXT": // Textbox
razorPageContent.AppendLine($@"<input type=""text""
id=""{textBoxId}"" name=""{textBoxId}"" class=""form-control"" style=""height:
{height}; width: {width};"" />");
break;

case "MSK": // Masked Input


razorPageContent.AppendLine($@"<input type=""text""
id=""{textBoxId}"" name=""{textBoxId}"" class=""form-control masked-input""
style=""height: {height}; width: {width};"" />");
break;
/*
case "SSEL": // Single Select Dropdown
DataRow[] fieldRows = tblFields.Select($"Fld_Code =
{controlCode}");
if (fieldRows.Length > 0)
{
DataRow fieldRow = fieldRows[0];
int fldCoded = Convert.ToInt32(fieldRow["Fld_Coded"]);
string fldCodedTable =
fieldRow["Fld_CodedTable"].ToString();
string fldLinkedField =
fieldRow["Fld_LinkedField"].ToString();
string fldCodedPrefix =
fieldRow["Fld_CodedPrefix"].ToString();
string fldDisplay = fieldRow["Fld_Display"].ToString();

// Generate dropdown
razorPageContent.AppendLine($@"
<select id=""{textBoxId}"" name=""{textBoxId}"" class=""form-
control"" style=""height: {height}; width: {width};"">
<option value="""">Select an option</option>");

// If Fld_Coded = 1, fetch values from database


if (fldCoded == 1)
{
var dropdownValues =
GetDropdownValues(fldCodedTable, fldCodedPrefix, fldLinkedField, fldDisplay);
foreach (var item in dropdownValues)
{
razorPageContent.AppendLine($@"<option
value=""{item.Value}"">{item.Text}</option>");
}
}

razorPageContent.AppendLine("</select>");
}
break;
*/
case "DAT": // Date Picker
razorPageContent.AppendLine($@"<input type=""date""
id=""{textBoxId}"" name=""{textBoxId}"" class=""form-control"" style=""height:
{height}; width: {width};"" />");
break;

case "IMG": // Image Button (Label becomes Button Text)


razorPageContent.AppendLine($@"
<button type=""button"" id=""{textBoxId}"" name=""{textBoxId}""
class=""btn btn-primary"" style=""height: {height}; width: {width};"">
{fieldLabel}
</button>");
break;

case "VAR": // Hidden Variable (No Label, Invisible)


razorPageContent.AppendLine($@"<input type=""hidden""
id=""{textBoxId}"" name=""{textBoxId}"" value="""" />");
break;
default: // Unknown control type (Fallback to text input)
razorPageContent.AppendLine($@"<input type=""text""
id=""{textBoxId}"" name=""{textBoxId}"" class=""form-control"" style=""height:
{height}; width: {width};"" />");
break;
}

// Close Input Section


razorPageContent.AppendLine("</div></div>");
}

// Close form with submit button


// razorPageContent.AppendLine(@"<div class=""text-center""><button
type=""submit"" class=""btn btn-success"">Submit</button></div>");
razorPageContent.AppendLine("</form>");

// Close Box Layout


razorPageContent.AppendLine("</div></div></div>");

// Save Razor Page


File.WriteAllText(filePath, razorPageContent.ToString());
}

/// <summary>
/// Fetches dropdown values from a lookup table
/// </summary>
private List<DropdownItem> GetDropdownValues(string tableName, string type,
string valueField, string displayField)
{
List<DropdownItem> dropdownValues = new List<DropdownItem>();

using (SqlConnection conn = new SqlConnection(_connectionString))


{
conn.Open();
string query = $"SELECT {valueField}, {displayField} FROM
{tableName} WHERE Type = @Type";

using (SqlCommand cmd = new SqlCommand(query, conn))


{
cmd.Parameters.AddWithValue("@Type", type);

using (SqlDataReader reader = cmd.ExecuteReader())


{
while (reader.Read())
{
dropdownValues.Add(new DropdownItem
{
Value = reader[valueField].ToString(),
Text = reader[displayField].ToString()
});
}
}
}
}

return dropdownValues;
}
}

public class DropdownItem


{
public string Value { get; set; }
public string Text { get; set; }
}
}

You might also like