c# - 未调用 HttpPost 方法
问题描述
当我运行我的代码时,我的 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 方法。看到这个问题。
要克服和解决您的问题,请将按钮包装在表单中,这样的事情应该可以解决问题。
@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>
}
推荐阅读
- python - 如何在数组数组中巧妙地转换 Pandas Dataframe?
- javascript - 如何循环遍历 htmlcollection 对象?
- r - ggplot2中条形图条的不同颜色
- java - IntelliJ 中单元测试的 Java 9 模块问题:不能需要 JUnit Jupiter
- java - URI 类的 Java 检测:添加依赖项会引发 ClassNotFoundException
- postgresql - pgadmin 4.28 数据库还原未完成
- javascript - “requestOptions”未定义
- python - 如何通过深度学习预测未来价值?
- c# - C# 转到循环的开头(继续还是中断?)
- javascript - 我可以根据 @param 类型的形状定义 JSDoc @return 类型吗?