Andrey Tagaew
Andrey Tagaew

Reputation: 1593

How to make MVC to select proper action in controller

Can somebody explain me one thing.

I have two methods in my controller :

public ActionResult AddPredefinedTicket(int customerId) {...}

and

public ActionResult AddPredefinedTicket(int customerId, TicketTypes type, string additionalJsonParameters) {...} (here TicketTypes is enum)

I'm tring to make a call with using URL like

http://.../Ticket/AddPredefinedTicket?customerId=1082

For some reason i got an exception :

The current request for action 'AddPredefinedTicket' on controller type 'TicketController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult AddPredefinedTicket(Int32) on type CallCenter.CustomerService.Controllers.TicketController System.Web.Mvc.ActionResult AddPredefinedTicket(Int32, CallCenter.CustomerService.Data.Models.TicketTypes, System.String) on type CallCenter.CustomerService.Controllers.TicketController

But, i don't understand why MVC think that the request is ambiguous. As you can see from my URL call, i'm not passing neither 'type' or 'additionalJsonParameters' parameters. I understand, that additionalJsonParameters is string, so it can be null.

But the action also has "type" parameter, that is enum and can't be null.

In my oppinion, MVC should use first action, but it don't.

Can you explain why ?

Upvotes: 2

Views: 602

Answers (3)

kmehta
kmehta

Reputation: 2497

Place the logic from the first method in the second method.

Put a check in there like

if(type==null && string.IsNullOrEmpty(additionalJsonParameters){
//do logic from method 1
}
else{
//do logic from method 2
}

Upvotes: 0

AJ.
AJ.

Reputation: 621

Did you forgot to decorate your methods with [HttpGet], [HttpPost] attributes.

Upvotes: 1

OhBugger
OhBugger

Reputation: 74

you cannot overload your ActionResults.

"There are some additional requirements that must be satisfied by a controller action. A method used as a controller action cannot be overloaded. Furthermore, a controller action cannot be a static method. Other than that, you can use just about any method as a controller action."

See : http://www.asp.net/Learn/mvc/tutorial-03-cs.aspx

Upvotes: 0

Related Questions