Various MVC4 actions based on GET variable

Is there a way to force MVC4 to call different actions based on the GET variable in the URL?

For example, suppose I have the following two actions.

[HttpPost] public ActionResult SubmitCrash(CrashReport rawData) { return View(); } [HttpPost] public ActionResult SubmitBug(BugReport data) { return View(); } 

Can the following URLs be used so that MVC4 "chooses" which action to invoke?

 http://MySite/Submit?Crash (calls 'SubmitCrash') http://MySite/Submit?Bug (calls 'SubmitBug') 

UPDATE:
I know very well that I can use actions / URLs as they are and do something with routing to make this happen (this is what I'm doing now), but I'm really interested in the GET vars question.

+6
source share
2 answers

This is not as neat as it could be, but you can use the "root" action for this:

 public ActionResult Submit(string method) { return Redirect("Submit"+method); } public ActionResult SubmitCrash() { return View(); } public ActionResult SubmitBug() { return View(); } 

Edit
I am extending ActionNameAttribute to meet your needs, so you can write this:

 //handles http://MySite/Submit?method=Crash [ActionNameWithParameter(Name = "Submit", ParameterName = "method", ParameterValue = "Crash")] public ActionResult SubmitCrash() { return View(); } //handles http://MySite/Submit?method=Bug [ActionNameWithParameter(Name = "Submit", ParameterName = "method", ParameterValue = "Bug")] public ActionResult SubmitBug() { return View(); } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class ActionNameWithParameterAttribute : ActionNameSelectorAttribute { public string Name { get; private set; } public string ParameterName { get; private set; } public string ParameterValue { get; private set; } public ActionNameAttribute(string name, string parameterName, string parameterValue) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name"); } this.Name = name; this.ParameterName = parameterName; this.ParameterValue = parameterValue; } public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { return string.Equals(actionName, this.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(controllerContext.HttpContext.Request.QueryString.Get(ParameterName) , this.ParameterValue , StringComparison.OrdinalIgnoreCase); } } 
+2
source

Why not create routes for this?

 routes.MapRoute( name: "SubmitCrash", url: "Submit/Crash", defaults: new { Action = "SubmitCrash", Controller = "NameOfController", }); routes.MapRoute( name: "SubmitBug", url: "Submit/Bug", defaults: new { Action = "SubmitBug", Controller = "NameOfController", }); 
+2
source

All Articles