首页 > 解决方案 > 如何将数据从视图传递到控制器的 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 在执行时为空。任何人都可以指导我正确实施吗?谢谢

标签: c#asp.net-mvc

解决方案


推荐阅读