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.
54 lines
1.7 KiB
54 lines
1.7 KiB
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
|
using Microsoft.AspNetCore.Mvc.Routing;
|
|
using Microsoft.AspNetCore.Routing;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System.Collections.Generic;
|
|
|
|
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)
|
|
{
|
|
MergeAttribute(context.Attributes, "data-ajax-url", GetUrl(context));
|
|
}
|
|
|
|
private string GetUrl(ClientModelValidationContext context)
|
|
{
|
|
return context.ActionContext.HttpContext.RequestServices.GetRequiredService<IUrlHelperFactory>()
|
|
.GetUrlHelper(context.ActionContext).RouteUrl(new UrlRouteContext
|
|
{
|
|
RouteName = RouteName,
|
|
Values = RouteData
|
|
});
|
|
}
|
|
|
|
private static void MergeAttribute(IDictionary<string, string> attributes, string key, string value)
|
|
{
|
|
if (!attributes.ContainsKey(key))
|
|
{
|
|
attributes.Add(key, value);
|
|
}
|
|
}
|
|
}
|
|
}
|