簡體   English   中英

在URL.Action中傳遞視圖模型

[英]Passing a View Model within a 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的文本嗎?

但是猜測一下,你可能想用Model = JSON.Encode(Model.Booking)替換Model = Model.Booking

哦。 而另一個概率。 您在Url操作中將參數命名為“Model”,但在方法簽名中命名為“createdModel”。

我發現了我的問題,所以我要為遇到同樣事情的人發布答案,並找到這個帖子。

因為URL Action中的兩個名稱都叫做Model,這會創建一個全新的ViewModel傳遞給視圖。 這是由於我的View中的事實,模型是我創建的動態模型,因此正在創建的Object是一個新的ExpandoObject。

解決方案是將ExpandoObject強制轉換為正確的類型,但我發現了一種使用TempData解決我的特定問題的不同方法。 無論哪種方式都有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM