Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions EditorFor/EditorFor.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30621.155
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EditorFor", "EditorFor\EditorFor.csproj", "{1257A071-1457-422B-9D74-631EE346B162}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1257A071-1457-422B-9D74-631EE346B162}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1257A071-1457-422B-9D74-631EE346B162}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1257A071-1457-422B-9D74-631EE346B162}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1257A071-1457-422B-9D74-631EE346B162}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {7E83487D-B9F8-471B-883C-33EC414BB619}
EndGlobalSection
EndGlobal
44 changes: 44 additions & 0 deletions EditorFor/EditorFor/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using EditorFor.Models;

namespace EditorFor.Controllers
{
public class HomeController : Controller
{

public IActionResult Index()
{
var testModel = new SomeEntity
{
IntProperty = 123,
LongProperty = 1234567890,
BoolProperty = true,
StringProperty = "Hello",
EnumProperty = Models.Enum.Option1,
ClassProperty = new NestedClass
{
NestedIntProperty = 9,
NestedStringProperty = "World"
}
};
return View(testModel);
}

public IActionResult Privacy()
{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
7 changes: 7 additions & 0 deletions EditorFor/EditorFor/EditorFor.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

</Project>
11 changes: 11 additions & 0 deletions EditorFor/EditorFor/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;

namespace EditorFor.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
31 changes: 31 additions & 0 deletions EditorFor/EditorFor/Models/SomeEntity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EditorFor.Models
{
public class SomeEntity
{
public int IntProperty { get; set; }
public long LongProperty { get; set; }
public bool BoolProperty { get; set; }
public string StringProperty { get; set; }
public Enum EnumProperty { get; set; }
public NestedClass ClassProperty { get; set; }
}

public enum Enum
{
Option1,
Option2,
Option3,
Option4
}

public class NestedClass
{
public int NestedIntProperty { get; set; }
public string NestedStringProperty { get; set; }
}
}
141 changes: 141 additions & 0 deletions EditorFor/EditorFor/MyEditorFor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace EditorFor
{
public static class MyEditorFor
{
public static IHtmlContent MyEditorForModel(this IHtmlHelper helper, object model)
{
var content = new HtmlContentBuilder();
foreach (var str in GetForm(model))
{
content.AppendHtml(str);
}

return content;
}

public static IHtmlContent MyEditorForProperty(this IHtmlHelper helper, object obj)
{
var content = new HtmlContentBuilder();
foreach (var str in Process(new PropertyNode(obj)))
{
content.AppendHtml(str);
}

return content;
}

private static readonly Dictionary<Type, string> InputTypes = new Dictionary<Type, string>
{
{typeof(int), "number"},
{typeof(long), "number"},
{typeof(bool), "checkbox"},
{typeof(string), "text"}
};

public static IEnumerable<string> GetForm(object obj)
{
var root = new PropertyNode(obj);
foreach (var str in root
.Type
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.SelectMany(p => Process(new PropertyNode(p.GetValue(obj), p, root))))
yield return str;
}

private static IEnumerable<string> Process(PropertyNode node)
{
yield return $"<div class='editor-label'><label for='{node.Name}'>{node.Name}</label></div>";

if (InputTypes.Keys.Contains(node.Type))
{
yield return GetInput(node);
}
else if (node.Type.IsEnum)
{
yield return GetSelect(node);
}
else if (node.Type.IsClass)
{
node.Parent.CheckType(node.Type);
foreach (var str in node
.Type
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.SelectMany(p => Process(new PropertyNode(p.GetValue(node.Value), p, node))))
yield return str;
}
else
{
throw new NotSupportedException("Модель содержит неподдерживаемые свойства");
}
}

private static string GetInput(PropertyNode node)
{
return $"<div class='editor-field'>" +
$"<input " +
$"type='{InputTypes[node.Type]}' " +
$"id='{node.Name}' " +
$"name='{node.Name}' " +
$"value='{node.Value}'" +
$"{Checked(node)}>" +
$"</div>";
}

private static string GetSelect(PropertyNode node)
{
return $"<div class='editor-field'>" +
$"<select name='{node.Name}'>" +
node
.Type
.GetEnumNames()
.Select(option =>
$"<option value='{option}'{Selected(node, option)}>{option}</option>")
.Aggregate((current, next) => current + next) +
$"</select>" +
$"</div>";
}

private static string Selected(PropertyNode node, string option)
{
return node.Value.ToString() == option ? " selected" : "";
}

private static string Checked(PropertyNode node)
{
return node.Type == typeof(bool) &&
(bool)node.Value ? " checked" : "";
}
}

class PropertyNode
{
public string Name { get; }
public PropertyNode Parent { get; }
public object Value { get; }
public Type Type { get; }

public PropertyNode(object value, PropertyInfo property = null, PropertyNode parent = null)
{
Value = value;
Type = value.GetType();
Name = property?.Name;
Parent = parent;
}

public void CheckType(Type type)
{
if (Type == type)
throw new NotSupportedException("Произошло зацикливание");

Parent?.CheckType(type);
}
}
}
26 changes: 26 additions & 0 deletions EditorFor/EditorFor/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace EditorFor
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
27 changes: 27 additions & 0 deletions EditorFor/EditorFor/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51034",
"sslPort": 44335
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"EditorFor": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
57 changes: 57 additions & 0 deletions EditorFor/EditorFor/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace EditorFor
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Loading