当我运行代码时,我的HttpGet方法似乎运行良好。但是,当我尝试将值返回到HttpPost操作时,它仅运行HttpGet方法,然后出现“ NullReferenceException”错误。

这是我的代码。

我在控制器中的操作:

[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();
        }


这是我的看法

@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>


我希望有人可以帮助我解决我的问题。

最佳答案

HTML ActionLink不适用于POST,因此正在命中GET方法。请参见this question

要解决并解决您的问题,请将按钮包装在表单中,这样的技巧应该可以解决。

@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>
}

关于c# - 不调用HttpPost方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60561464/

10-11 00:52