【发布时间】: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