有没有办法让MVC4根据URL中的GET变量调用不同的动作?
例如,假设我有以下两个动作。
[HttpPost]
public ActionResult SubmitCrash(CrashReport rawData)
{
return View();
}
[HttpPost]
public ActionResult SubmitBug(BugReport data)
{
return View();
}
有没有办法让我可以使用以下网址让MVC4'选择'要调用哪个动作?
http://MySite/Submit?Crash (calls 'SubmitCrash')
http://MySite/Submit?Bug (calls 'SubmitBug')
更新
我非常清楚我可以按照它们的方式使用动作/ URL,并使用路由来实现它(这就是我现在正在做的事情),但我真的对GET vars部分问题感兴趣。
答案 0 :(得分:2)
为什么不创建路由来执行此操作?
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",
});
答案 1 :(得分:2)
它不尽可能整洁,但你可以使用'root'动作:
public ActionResult Submit(string method)
{
return Redirect("Submit"+method);
}
public ActionResult SubmitCrash()
{
return View();
}
public ActionResult SubmitBug()
{
return View();
}
修改强>
我已经扩展了ActionNameAttribute以满足您的需求,因此您可以这样写:
//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);
}
}