c# - 在 URL.Action 中传递视图模型
问题描述
我正在尝试将视图模型传递给我的控制器。
@if (User.IsInRole("Customer"))
{
<input type="button" class="btn btn-danger" value="Rent Car" onclick="location.href='@Url.Action("PassingCar", "Bookings", new { id = item.VehicleID, Model = Model.Booking })'" />
}
我正在使用动态模型,因此我可以在此视图中同时使用 Vehicle 和 Booking。
当代码到达我的控制器时,ID 已被传递,但 ViewModel 中的数据消失了。
public ActionResult PassingCar( int id, CreateBookingViewModel createdModel)
{
///Checks that Vehicle exists in DB and v property is not null
if (v == null)
{
return HttpNotFound();
}
else
{
/// sets the Vehicle attribute of the BookingViewModel to vehicle passed over
createdModel.Vehicle = v;
}
return RedirectToAction("Create", "Bookings");
}
如果有人知道我做错了什么,将不胜感激。
解决方案
我发现了我的问题,所以我将为遇到相同问题的任何人发布答案,并找到该线程。
因为 URL Action 中的两个名称都称为 Model,所以这将创建一个传递给视图的全新 ViewModel。这是因为在我的视图中,模型是我创建的动态模型,因此正在创建的对象是新的 ExpandoObject。
一种解决方案是将 ExpandoObject 转换为正确的类型,但我发现了一种仅使用 TempData 来解决我的特定问题的不同方法。无论哪种方式都会奏效。
推荐阅读
- python - Airflow - GCP Operator:GoogleCloudStorageToBigQueryOperator - 需要 15 分钟才能完成
- python - python中的双重提醒操作
- r - 使用 Rcpp 模块通过派生对象公开继承的方法
- javascript - PHP如何将已经上传的文件保留在编辑表单中
- javascript - 尝试访问表单数据时发生综合事件错误
- android-studio - 构建 android OCR tesseract 时未找到数据文件错误,因此无法查看 OCR 结果
- java - 有没有办法解决 upi_pay: ^0.2.0 插件和 razorpay_flutter: ^1.2.2 插件之间的冲突,并在 android 应用程序中同时使用两者
- reactjs - 如何在反应中包含动画 CDN
- reinforcement-learning - DQN:在将观察空间转换为 Box 环境后访问原始观察结果?
- python - 如何将函数作为变量运行?