0

I am learning Async/Await in MVC5. I created this demo app but my controller action method is not getting fired. Its giving "The resource cannot be found." error. Here is the code.

  1. _Layout.cshtml view

    @Html.ActionLink("ASYNC", "GetNames", "Async")
    
  2. GetNames.cshtml view

    @Html.ActionLink("Click Me", "GetFirstName", "Async", null,  new{@class = "btn btn-primary" })
    @if (ViewBag.FName != null)
    {
      <p>
         <label>@ViewBag.FName </label>
      </p>
    }
    
  3. In AsyncController.cs file

    public ActionResult GetNames()
    {
        return View();
    }
    
    [HttpPost]
    public async Task<ActionResult> GetFirstName()
    {
        var r = await GetFirstNameFromDB();
        ViewBag.FName = r;
        return View("GetNames");
    }
    public async Task<string> GetFirstNameFromDB()
    {
        try
        {
            var res = await Task.Run(() =>
            {
                Thread.Sleep(3000);
                return "TestFName";
            });
    
            return res;
        }
        catch (Exception)
        {
            return "Error in getting FirstName";
        }
    }
    

Now, whenever i click the action link button to call the GetFirstName, it shows The resource cannot be found. error. I'm not sure if it is related to action being async or something else.

3
  • Have you hit F12 to see what exactly is being called when you click the button? Commented Feb 18, 2016 at 17:18
  • 1
    ActionLink produces an <a> anchor tag. Clicking on these generates a GET request. However your action is marked [HttpPost]. Commented Feb 18, 2016 at 17:21
  • As Jasen mentioned. Change the HttpPost to HttpGet or remove it altogether. Commented Feb 18, 2016 at 17:25

1 Answer 1

6

You have defined an ActionLink which will perform a GET-request when you click on it.

The controller has the method GetFirstName defined as HttpPost. Changing this to HttpGet will make sure the action is available for GET-requests.

Sign up to request clarification or add additional context in comments.

1 Comment

sometimes trying to learn big make you overlook small things :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.