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.
47 lines
1.7 KiB
47 lines
1.7 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.Reflection;
|
|
|
|
namespace System.ComponentModel.DataAnnotations
|
|
{
|
|
public class AjaxSelectAttribute : UIHintAttribute, IClientModelValidator
|
|
{
|
|
public string Action { get; }
|
|
public string Controller { get; }
|
|
public string Area { get; }
|
|
protected RouteValueDictionary RouteData { get; } = new RouteValueDictionary();
|
|
public AjaxSelectAttribute(string action, string controller, string area = null) : base("AjaxSelect")
|
|
{
|
|
this.Action = action;
|
|
this.Controller = controller;
|
|
this.Area = area;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
private string GetUrl(ClientModelValidationContext context)
|
|
{
|
|
var scope = (context.ActionContext.ActionDescriptor as ControllerActionDescriptor)
|
|
.ControllerTypeInfo
|
|
.GetCustomAttribute<ControllerScopeAttribute>();
|
|
var url = context.ActionContext.HttpContext.RequestServices.GetRequiredService<IUrlHelperFactory>()
|
|
.GetUrlHelper(context.ActionContext).Action(Action, Controller, new { area = Area, range = scope?.Scope });
|
|
return url;
|
|
}
|
|
}
|
|
}
|