简体   繁体   English

在URL.Action中传递视图模型

[英]Passing a View Model within a URL.Action

I'm trying to pass a view model to my controller. 我正在尝试将视图模型传递给我的控制器。

 @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 })'" />

            }

I'm using a dynamic model so I can use both Vehicle and Booking in this view. 我正在使用动态模型,因此我可以在此视图中同时使用Vehicle和Booking。

When the code gets to my controller the ID has been passed over but the data in the ViewModel is gone. 当代码到达我的控制器时,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");
        }

If anybody has an idea what i'm doing wrong it would be greatly appreciated. 如果有人知道我做错了什么,我将不胜感激。

Can you post the text of the URL you end up at? 您可以发布最终到达的URL的文本吗?

But at a guess, you might want to replace Model = Model.Booking with Model = JSON.Encode(Model.Booking) 但是猜测一下,你可能想用Model = JSON.Encode(Model.Booking)替换Model = Model.Booking

Oh. 哦。 And another probability. 而另一个概率。 You name the parameter "Model" in the Url Action, but "createdModel" in the method signature. 您在Url操作中将参数命名为“Model”,但在方法签名中命名为“createdModel”。

I discoverer my problem so I'm gonna post an answer for anyone encountering the same thing, and find this thread. 我发现了我的问题,所以我要为遇到同样事情的人发布答案,并找到这个帖子。

Because both of the names in the URL Action where called Model, this would create a brand new ViewModel passed to the view. 因为URL Action中的两个名称都叫做Model,这会创建一个全新的ViewModel传递给视图。 This was due to the fact in my View, the model was a dynamic model I created so the Object that was being created was anew ExpandoObject. 这是由于我的View中的事实,模型是我创建的动态模型,因此正在创建的Object是一个新的ExpandoObject。

A solution would of been to cast the ExpandoObject to the correct type, but I discovered a different way to solve my specific problem just using TempData. 解决方案是将ExpandoObject强制转换为正确的类型,但我发现了一种使用TempData解决我的特定问题的不同方法。 Either way would of worked. 无论哪种方式都有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM