【问题标题】:HttpPost method is not called未调用 HttpPost 方法
【发布时间】:2020-03-06 19:14:24
【问题描述】:

当我运行我的代码时,我的 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>

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

【问题讨论】:

  • 附注:第一个方法可能有 GetMovie 名称,因为它是 Get 方法,而不是 post 方法。对于您的问题,您是否尝试在 post 方法上放置一个 BP 并检查它是否被命中?并确定您在哪一行得到异常
  • 整数? id -> 你的参数在 get 中可以为空并且你正在使用它,还应该添加电影,因为你试图坚持一些东西
  • @KristófTóth 不,Html.ActionLink 有两个参数应该命中 post 方法,而不是 Get 一个!
  • 您需要将视图包装在一个表单中,以便数据实际上作为 POST 发送
  • "但是当我尝试将值返回给我的 HttpPost 操作时,它只会运行我的 HttpGet 方法"...因为 ActionLink(生成 HTML 超链接)总是会导致 GET 请求。如果要发布,则必须使用表单。

标签: c# asp.net-core-mvc


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多