首页 > 解决方案 > 在 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");
        }

如果有人知道我做错了什么,将不胜感激。

标签: c#asp.netmodel-view-controllerasp.net-mvc-5viewmodel

解决方案


我发现了我的问题,所以我将为遇到相同问题的任何人发布答案,并找到该线程。

因为 URL Action 中的两个名称都称为 Model,所以这将创建一个传递给视图的全新 ViewModel。这是因为在我的视图中,模型是我创建的动态模型,因此正在创建的对象是新的 ExpandoObject。

一种解决方案是将 ExpandoObject 转换为正确的类型,但我发现了一种仅使用 TempData 来解决我的特定问题的不同方法。无论哪种方式都会奏效。


推荐阅读