I have a table of records being displayed in a partial view and some of them have no ID values. So I am trying to use an alternative field as an ID when clicking the Edit link for a particular record. I'm not sure if I can legally have two Post action methods, even though I am using different methods names and params.
Currently, if I click on a record with an ID the correct action method gets called. If I select a record with no ID (instead using an "account" string ID which is unique), I get a 404.
RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Partial View:
...
<td>
@if (item.ID != null)
{
@Html.ActionLink("Edit", "EditBudget", new { id = item.ID })
}
else if (item.Account != null)
{
@Html.ActionLink("Edit", "EditAccountBudget", new { account = item.Account })
}
</td>
BudgetsController:
// POST: Budgets/Edit/5
[Route("edit/{id?}")]
[HttpPost]
public ActionResult EditBudget(int? id = null, FormCollection collection = null)
{
...
// Responding correctly for URL: http://localhost:4007/edit/19
}
[Route("editaccountbudget/{account}")]
[HttpPost]
public ActionResult EditAccountBudget(string account)
{
...
// Getting 404 for URL: http://localhost:4007/editaccountbudget/6000..130
}
As some have pointed out, this is a GET request. If the ID was null, I had to pass the model because I needed more than the account ID to construct the database query.
Partial View:
@if (item.ID != null)
{
@Html.ActionLink("Edit", "EditBudget", new { id = item.ID })
}
else if (item.Account != null)
{
@Html.ActionLink("Edit", "EditBudget", new { account = item.Account,
SelectedDepartment = item.SelectedDepartment, SelectedYear = item.SelectedYear })
}
BudgetsController:
// GET
public ActionResult EditBudget(int? id, BudgetsViewModel model)
{
repo = new BudgetDemoRepository();
if (id != null)
{
// Pass id to repository class
}
else
{
// Pass account and other params to repository class
}
return View(...);
}