Good day. I am trying to write a controller in the mvc 5 project with an overloaded method. The task is to enter a value in the field, and display information, the contents of this value from the repository in the overloaded method.

When you enter a value in the field, an error is displayed:

The current request for the "SearchForGift" action on the "GiftController" type controller is ambiguous on the following action methods: System.Web.Mvc.ActionResult SearchForGift (System.String) on ​​the NewYearGifts.WebUI.Controllers.GiftController type System.Web.Mvc.ViewResultForGG.Controllers.GiftController (System.String, Int32) on type NewYearGifts.WebUI.Controllers.GiftController).

Thanks for the help.

GiftController (controller)

[HttpGet] public ActionResult SearchForGift() { return View(repository.Gifts); } [HttpPost] public ActionResult SearchForGift(string searchTerm) { return View(repository.Gifts.Where(g => g.Name.StartsWith(searchTerm))); } 

SearchForGift.cshtml (view field)

 @using (@Html.BeginForm("SearchForGift", "Gift", FormMethod.Post)) { <b>Name: </b> @Html.TextBox("searchTerm", null, new { id = "txtSearch" }) <input type="submit" value="Search" /> } 
  • one
    SearchForGift(System.String, Int32) - where? - Igor

1 answer 1

The controller should have two methods with the same name, the attribute [HttpGet] should be applied to one of them, and [HttpGet] to the other.

In your case, there are two methods in the controller: SearchForGift() and SearchForGift(string searchTerm) , but there is also a third SearchForGift(System.String, Int32)

Option 1

You can fix the error by renaming the third method.

Option 2

You can also combine the SearchForGift(System.String) and SearchForGift(System.String, Int32) methods into one

 [HttpPost] public ActionResult SearchForGift(string searchTerm, int? param) { if (param == null) { //поиск по параметру searchTerm var model = repository.Gifts.Where(g => g.Name.StartsWith(searchTerm)); return View(model); } else { //поиск по двум параметрам var model = repository.Gifts.Where(g => g.Name.StartsWith(searchTerm) && p => p.Id == param); return View(model); } }