remco
remco

Reputation: 75

HttpPost method is not called

when I run my code it seems that my HttpGet method works fine. But when I try to return the value to my HttpPost action it just runs my HttpGet method and then I get an "NullReferenceException" error.

Here is my code.

My Actions in my controller:

[HttpGet]
        public IActionResult AddMovie(int? id)
        {
            List<Movie> movieList = new List<Movie>();
            movieList = dbContext.Movies.ToList();

            AddMovieViewModel viewModel = new AddMovieViewModel()
            {
                movies = movieList,
                customer = dbContext.Customers.Where(s => s.CustomerId == id).FirstOrDefault()
            };

            return View(viewModel);
        }

        [HttpPost]
        public IActionResult AddMovie (int id,int cid)
        {
            Customer customer = dbContext.Customers.Where(s => s.CustomerId == cid).FirstOrDefault();
            Movie movie = dbContext.Movies.Where(s => s.MovieId == id).FirstOrDefault();
            customer.BorrowingMovies.Add(movie);
            customer.BorrowingMovies.Add(movie);
            return View();
        }

And here my view

@model MovieExampleAppDotNetCore.ViewModels.AddMovieViewModel
@{
    ViewData["Title"] = "AddMovie";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>AddMovie</h1>

<label>Add movie for: @Model.customer.Name</label>

<table style="width:100%" class="table table-bordered table-hover">
    <tr>
        <th>Name</th>
    </tr>
        @foreach (var movie in Model.movies)
     {
            <tr>
                <td>@movie.Name</td>
             <td>
                    @Html.ActionLink("Select", "AddMovie", new { id = movie.MovieId, cid = Model.customer.CustomerId })
             </td>
          </tr>
        }
</table>

I hope someone can help me with my problem.

Upvotes: 2

Views: 1305

Answers (1)

Ryan Thomas
Ryan Thomas

Reputation: 2002

The HTML ActionLink does not work with POST so is hitting your GET method. See this question.

To overcome and resolve your issue, wrap the button in a Form, something like this should do the trick.

@using (Html.BeginForm("AddMovie", "ControllerName", new { id = movie.MovieId, cid = Model.customer.CustomerId }, FormMethod.Post))
{
    <button class="btn btn-primary" type="submit">
        Add Movie
    </button>
}

Upvotes: 5

Related Questions