Search code examples
c#asp.netasp.net-mvcrazor

ASP.NET "Resource not found" when attempting to execute an ActionResult method in the controller


I am trying to add an Edit functionality to my MVC5 application, but whenever I try to call my Edit method in the Search view, I get an error saying that the resource localhost:xxxx/Search/EditClient doesn't exist.

EditClient is just a method in my controller, and I have to return a RedirectToAction.

Here's my controller:

public class SearchController : Controller 
{
    public ActionResult SearchClient() {
        //Just returning the default view for the search page
        return View();
    }

    public ActionResult SearchClient(string SearchId)
    {
        //I do have validations in case the ID doesn't exist, but I'm omitting them from this question to avoid inflating the code.
        Client clientFound = (Client)Session[SearchId];
        //SearchId is the ID attribute for my Client object. If the ID was in the Session variable, it will retrieve the corresponding object and I'll use it for the model in my view.
        return View("SearchClient", clientFound);
    }

    [HttpPost]
    public ActionResult EditClient(Client client)
    {
        Session[client.Id] = client;
        return RedirectToAction("SearchClient");
    }
}

My View

@model MVCExample.Models.Client

@{
    ViewBag.Title = "Search";
    ViewBag.Message = "Look for Clients";
}

<h1 class="store-title">@ViewBag.Title</h1>
<h2 class="page-title">@ViewBag.Message</h2>
@using (Html.BeginForm("SearchClient", "Search"))
{
   <p>Search for User ID: @Html.TextBox("SearchId")</p></br>
   <input type="submit" value="Search"/>

   @Html.LabelFor(m => m.FullName), new { @class = "control-label" }
   @Html.EditorFor(m => m.FullName, new { @class = "form-control" }

   <a class="btn btn-primary" href="@Url.Action("EditClient, "Search", FormMethod.Post)">Save Changes</a>
}

I can successfully retrieve a user and have their data displayed, but whenever I try to change it (In this example I only created a field for FullName, but I have fields for every property) and save the changes, I get redirected to an error page saying that Search/EditClient doesn't exist. I thought that redirecting to an action would fix that, so why does it seem like my app is trying to display the wrong view?


Solution

  • Ancor tag always generates a Get method. It doesn't submit a form, it just calls a GET action with provided parameters. If you want to POST a form it is better to use a button. And you need to call EditClient action. Try this

     @using (Html.BeginForm("EditClient", "Search",  FormMethod.Post))
        {
    ..... your code
           <input type="submit" class="btn btn-primary" value="Save Changes"/>
        }
    

    I can't see your startup file so maybe you can try to use routing

        [Route("~/Search/EditClient")]
        public ActionResult EditClient(Client client)
        {
     .....
         }