c# - 基于 GET 变量的不同 MVC4 Action

标签 c# asp.net-mvc-4 asp.net-mvc-routing

有没有办法让 MVC4 根据 URL 中的 GET 变量调用不同的操作?

例如,假设我有以下两个操作。

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


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

有没有一种方法可以使用以下 URL 让 MVC4“选择”要调用的操作?

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

更新:
我非常清楚我可以按原样使用操作/url,并通过路由来实现它(这就是我现在正在做的),但我真的对问题的 GET vars 部分感兴趣。

最佳答案

它并不像它应该的那样整洁,但您可以为此使用“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);
    }
}

关于c# - 基于 GET 变量的不同 MVC4 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15528060/

相关文章:

c# - ASP.NET MVC - 创建没有后备的自定义路由

c# - MongoDB geonear 和文本命令驱动程序 2.0

c# - 使用 DigitalPersona 4500 读取器进行指纹扫描。如何获取捕获的图像和加载事件处理程序

c# - 如何检查两个.wav文件是否包含相同的声音数据?

javascript - 使用ajax从 Controller 到JS的日期字符串

c# - 为 SEO 友好的博客正确设置自定义路由

c# - 在 C# 中用于回归的免费库

entity-framework - Entity Framework 代码首先不使用 VS 2012 创建表

c# - 在 mvc .net (system.data.common.dbconnection) 中建立连接时出错

asp.net-mvc - 在 ASP.NET MVC 4 中使用和不使用 Controller 名称的路由