简体   繁体   中英

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.

When the code gets to my controller the ID has been passed over but the data in the ViewModel is gone.

 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?

But at a guess, you might want to replace Model = Model.Booking with Model = JSON.Encode(Model.Booking)

Oh. And another probability. You name the parameter "Model" in the Url Action, but "createdModel" in the method signature.

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. 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.

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. Either way would of worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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