c# - 如何将数据从视图传递到控制器的 post 端点?
问题描述
我可以通过这样的 ViewModel 查看数据库中的数据:
[HttpGet]
[Authorize]
public ActionResult Rent(int id)
{
Helper helper = new Helper();
var cars = _context.Cars.Find(id);
var useremail = User.Identity.Name;
var username = helper.GetName(User.Identity.GetUserId());
var viewmodel = new RentalViewModel
{
UserName = username,
UserEmail = useremail,
CarMake = cars.Make,
CarMod = cars.Mod,
CarPicture = cars.Picture,
CarPrice = cars.Price,
CarId = cars.Id
};
return View(viewmodel);
}
这在视图中效果很好,我可以在其中调用我需要的数据。
现在我要做的是按下一个按钮,然后执行一个 HttpPost 方法,该方法将获取这些数据并将其保存在一个名为 Rental 的表(模型)中。
这是我的代码:
[HttpPost]
public ActionResult RentPost(RentalViewModel model)
{
var rentals = new Rental
{
CarId = model.CarId
};
_context.Rentals.Add(rentals);
_context.SaveChanges();
return RedirectToAction("About", "Home");
}
这是我的观点:
@using (Html.BeginForm("RentPost", "Home", new {id = @Model.CarId}))
{
<h1> @Model.UserName </h1>
<h1> @Model.UserEmail </h1>
<h1> @Model.CarMake @Model.CarMod </h1>
<h1> </h1>
<img src="@Model.CarPicture" alt="" />
<h1> {@Model.CarPrice*3} </h1>
@Html.DisplayFor(m=>m.CarId)
<button type="submit" class="btn btn-primary"> Save </button>
}
我现在只传递一个元素只是为了测试目的,也出于同样的原因重定向。调试后,CarId 为 NULL,这是可以理解的,因为 ViewModel 在执行时为空。任何人都可以指导我正确实施吗?谢谢
解决方案
推荐阅读
- android - 检测到 Android.Malware.General(得分:6)引擎
- java - Java 在不应该返回任何内容时一直返回 0
- ios - 如何在多值部分获取行顺序信息?
- azure - Azure SQL 中的“用户登录失败”为“打开时底层提供程序失败”
- amazon-web-services - 如果收到消息,AWS SQS 长轮询是否会提前返回?
- reactjs - 通过键过滤对象的对象
- spring - 在spring boot中每月自动创建带有后缀的实体
- x86-64 - 带 SSE 的 8 位 LERP
- java - 构建 Java netty SslContext 和 apache SSLContexts 以信任来自动态 .pem 文件的证书,而无需预加载信任库
- javascript - Chrome/Safari 基本测试:使用 IP 地址而不是 localhost 时,CSS、Javascript、图像不起作用,因为它正在“https”中查找文件