using System;
using System.Reflection;
using System.Text;
public class ModelToHtmlConverter
{
public static string GenerateFormHtml<T>()
{
var sb = new StringBuilder();
var type = typeof(T);
sb.Append("<form method=\"post\">");
foreach (var property in type.GetProperties())
{
var label = property.Name;
var inputType = GetInputType(property.PropertyType);
sb.Append($"<div class=\"form-group row mb-3\">");
sb.Append($"<label class=\"col-md-2 col-form-label\">{label}:</label>");
if (inputType == "select")
{
sb.Append($"<select name=\"{label}\">");
foreach (var option in GetOptions(property.PropertyType))
{
sb.Append($"<option value=\"{option}\">{option}</option>");
}
sb.Append($"</select>");
}
else
{
sb.Append($"<input type=\"{inputType}\" name=\"{label}\" />");
}
sb.Append($"</div>");
}
sb.Append("<button type=\"submit\">Submit</button>");
sb.Append("</form>");
return sb.ToString();
}
private static string GetInputType(Type type)
{
if (type == typeof(string))
return "text";
else if (type == typeof(int) || type == typeof(double) || type == typeof(float))
return "number";
else if (type == typeof(bool))
return "checkbox";
else if (type == typeof(DateTime))
return "date";
else if (type.IsEnum)
return "select";
else
return "text";
}
private static string[] GetOptions(Type type)
{
if (type.IsEnum)
return Enum.GetNames(type);
else
return new string[0];
}
}
// Example usage:
public enum Gender
{
Male,
Female,
Other
}
public class MyModel
{
public string Name { get; set; } = null!;
public string Number { get; set; } = null!;
public string? Address1 { get; set; }
public string? Address2 { get; set; }
public string? Address3 { get; set; }
public string? Address4 { get; set; }
public string? City { get; set; }
public string? State { get; set; }
public string? Zip { get; set; }
public PaymentTermsId PaymentTermsId { get; set; }
public bool IsDeleted { get; set; }
public string CreatedBy { get; set; } = null!;
public DateTime CreatedOn { get; set; }
public string ModifiedBy { get; set; } = null!;
public DateTime? ModifiedOn { get; set; }
}
public enum PaymentTermsId
{
Male,
Female,
Other
}
class Program
{
static void Main(string[] args)
{
string formHtml = ModelToHtmlConverter.GenerateFormHtml<MyModel>();
Console.WriteLine(formHtml);
}
}
No comments:
Post a Comment