Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在参数不同的情况下,如何定义操作asp.net mvc4_Asp.net_Asp.net Mvc 4 - Fatal编程技术网

在参数不同的情况下,如何定义操作asp.net mvc4

在参数不同的情况下,如何定义操作asp.net mvc4,asp.net,asp.net-mvc-4,Asp.net,Asp.net Mvc 4,我尝试为diff参数定义操作,但不起作用: public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Index(string name) { return new JsonResult(); } public ActionResult Index

我尝试为diff参数定义操作,但不起作用:

public class HomeController : Controller
  {
    public ActionResult Index()
    {
      return  View();
    }

    public ActionResult Index(string name)
    {
      return new JsonResult();
    }

    public ActionResult Index(string lastname)
    {
      return new JsonResult();
    }

    public ActionResult Index(string name, string lastname)
    {
      return new JsonResult();
    }
    public ActionResult Index(string id)
    {
      return new JsonResult();
    }
 }
但我得到了一个错误:

控制器类型“HomeController”的当前操作请求“索引”在以下操作方法之间不明确。

编辑:

如果不可能,请建议最好的方法。

谢谢

Yosef

您可以使用以下属性:

[ActionName("ActionName")]

然后,每个操作方法都有不同的名称。

当它们响应相同类型的请求(GET、POST等)时,不能有重载的操作方法。您应该有一个带有所有所需参数的公共方法。如果请求没有提供它们,它们将为null,您可以决定使用哪个重载

对于这个单一的公共方法,您可以通过定义模型来利用默认模型绑定

public class IndexModel
{
    public string Id { get; set;}
    public string Name { get; set;}
    public string LastName { get; set;}
}
以下是控制器的外观:

public class HomeController : Controller
{
    public ActionResult Index(IndexModel model)
    {
        //do something here
    }
}

这两者不能共存,因为编译器无法区分它们。重命名或删除它们,或添加其他参数。这适用于所有类别

public ActionResult Index(string name) 
{ 
  return new JsonResult(); 
} 

public ActionResult Index(string lastname) 
{ 
  return new JsonResult(); 
}
尝试使用具有默认参数的单个方法:

    public ActionResult Index(int? id, string name = null, string lastName = null)
    {
        if (id.HasValue)
        {
            return new JsonResult();
        }

        if (name != null || lastName != null)
        {
            return new JsonResult();
        }

        return View();
    }


所有的动作都只得到http(像web服务)谢谢,yopu能给我写的例子吗?
    public ActionResult Index(int id = 0, string name = null, string lastName = null)
    {
        if (id > 0)
        {
            return new JsonResult();
        }

        if (name != null || lastName != null)
        {
            return new JsonResult();
        }

        return View();
    }