Ben
Ben

Reputation: 25807

How define action in the case of different parameters? - asp.net mvc4

I try define actions for diff params but its not working:

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();
    }
 }

but i get error:

The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods ....

Edit:

If it not possible please suggest the best way to do it.

Thanks,

Yosef

Upvotes: 1

Views: 866

Answers (3)

Chris Gessler
Chris Gessler

Reputation: 23113

These two can't live together because the compiler can't tell them apart. Either rename them or delete one, or add an additional param. This is true for all classes.

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

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

Try using a single method with default parameters:

    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();
    }

OR

    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();
    }

Upvotes: 1

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

You cannot have overloaded action methods when they respond to same type of requests(GET, POST etc.). You should have a single public method with all the parameters you need. If the requests don't provide them they will be null and you can decide which overload you can use.

For this single public method you can take advantage of default model binding by defining a model.

public class IndexModel
{
    public string Id { get; set;}
    public string Name { get; set;}
    public string LastName { get; set;}
}

Here's how your controller should look like:

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

Upvotes: 1

Alex
Alex

Reputation: 35409

You could use the ActionNameAttribute attribute:

[ActionName("ActionName")]

Then, you'd have different names for each of the Action methods.

Upvotes: 1

Related Questions