Created
April 14, 2012 01:30
-
-
Save jsakamoto/2381357 to your computer and use it in GitHub Desktop.
ASP.NET MVC Data Annotation Valiteion - Remote Validation with Server Side Validation!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NOTICE: | |
// This is "concept" sample code. | |
// Not enough resouce disposing, etc. | |
public class MyRemoteAttribute : RemoteAttribute | |
{ | |
public RemotableCustomAttribute(string action, string controller) : base(action, controller) | |
{ | |
} | |
public string ControllerName { get { return this.RouteData["controller"] as string; } } | |
public string ActionName { get { return this.RouteData["action"] as string; } } | |
// | |
// Server side validation here! | |
// | |
public override bool IsValid(object value) | |
{ | |
if (value == null) return true; | |
// Create instance of ASP.NET MVC Controler. | |
var context = new HttpContextWrapper(HttpContext.Current); | |
var routeData = new RouteData(); | |
var requestContext = new RequestContext(context, routeData); | |
var controller = ControllerBuilder.Current | |
.GetControllerFactory() | |
.CreateController(requestContext, controllerName); | |
// Invoke action method, and eval return value. | |
var result = controller.GetType().InvokeMember( | |
this.ActionName, | |
BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, | |
null, | |
controller, new object[] { value } | |
) as JsonResult; | |
var isValid = (result.Data is bool) && ((bool)result.Data); | |
return isValid; | |
} | |
} |
SOLUTION TO THIS PROBLEM:
//var context = new HttpContextWrapper(HttpContext.Current);
//var routeData = new RouteData();
//var requestContext = new RequestContext(context, routeData);
var requestContext = HttpContext.Current.Request.RequestContext;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is an issue about this solution. In-case if you have controllers with the same name in some Areas, you will face a problem.
Multiple types were found that match the controller named 'Company'. This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.
The request for 'Company' has found the following matching controllers:
NPIIS.Web.MVC.Areas.ControlPanel.Controllers.CompanyController
NPIIS.Web.MVC.Controllers.CompanyController
var controller = ControllerBuilder.Current <= PROBLEM