You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.8 KiB
79 lines
2.8 KiB
using Infrastructure.Web.Mvc;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Controllers;
|
|
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
|
using Microsoft.AspNetCore.Mvc.Routing;
|
|
using Microsoft.AspNetCore.Routing;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
|
|
namespace System.ComponentModel.DataAnnotations
|
|
{
|
|
public class AjaxSelectAttribute : UIHintAttribute, IClientModelValidator
|
|
{
|
|
protected string RouteName { get; set; }
|
|
protected RouteValueDictionary RouteData { get; } = new RouteValueDictionary();
|
|
public AjaxSelectAttribute(string action, string controller, string areaName = null) : base("AjaxSelect")
|
|
{
|
|
if (action != null)
|
|
{
|
|
RouteData["action"] = action;
|
|
}
|
|
if (controller != null)
|
|
{
|
|
RouteData["controller"] = controller;
|
|
}
|
|
if (controller != null)
|
|
{
|
|
RouteData["area"] = areaName;
|
|
}
|
|
}
|
|
|
|
public void AddValidation(ClientModelValidationContext context)
|
|
{
|
|
var key = "data-ajax-url";
|
|
var value = GetUrl(context);
|
|
var attributes = context.Attributes;
|
|
if (!attributes.ContainsKey(key))
|
|
{
|
|
attributes.Add(key, value);
|
|
}
|
|
}
|
|
public string GetAjaxUrl(IUrlHelper url)
|
|
{
|
|
var scope = (url.ActionContext.ActionDescriptor as ControllerActionDescriptor)
|
|
.ControllerTypeInfo
|
|
.GetCustomAttribute<ControllerScopeAttribute>();
|
|
var key = "range";
|
|
if (scope != null && !RouteData.ContainsKey(key))
|
|
{
|
|
RouteData.Add(key, scope.Scope);
|
|
}
|
|
return url.RouteUrl(new UrlRouteContext
|
|
{
|
|
RouteName = RouteName,
|
|
Values = RouteData
|
|
});
|
|
}
|
|
private string GetUrl(ClientModelValidationContext context)
|
|
{
|
|
var scope = (context.ActionContext.ActionDescriptor as ControllerActionDescriptor)
|
|
.ControllerTypeInfo
|
|
.GetCustomAttribute<ControllerScopeAttribute>();
|
|
var key = "range";
|
|
if (scope != null && !RouteData.ContainsKey(key))
|
|
{
|
|
RouteData.Add(key, scope.Scope);
|
|
}
|
|
var url = context.ActionContext.HttpContext.RequestServices.GetRequiredService<IUrlHelperFactory>()
|
|
.GetUrlHelper(context.ActionContext).RouteUrl(new UrlRouteContext
|
|
{
|
|
RouteName = RouteName,
|
|
Values = RouteData
|
|
});
|
|
return url;
|
|
}
|
|
}
|
|
}
|