简体   繁体   中英

MVC Model Binding Complex Type to Action Parameter

I'm binding a list of customers into a customer search results page using the model binding of MVC3, and using Razor to render all the customers in a foreach loop. My question is how then to send back the customer object to the action to save me having to fetch the details again.

Below is my action method signature:

public ActionResult BasketAddCustomer(Customer customer)

The Customer object is quite large, ie. lots of fields

Below is a cut down version of the view which renders each customer and has the button to select each one.

@model WebUI.Models.SearchModel
@foreach (var customer in Model.Customers)
    {
                <h5>@customer.FirstName @customer.LastName</h5>
                <button onclick="window.location.href = '@Url.Action("BasketAddCustomer", "Cust", customer)';">Select customer</button>                    
    }

The problem with this is that the customer that is passed into the action seems to come through as being full of nulls.

The html that is rendered by the @URL.Action is below and looks like a good start but only has some of the customer fields, not all. Is the Customer just too complex for being broken down this way? Is there a better way to do it?

<button onclick="window.location.href = 
'/Test/Cust/BasketAddCustomer?BirthDate=01%2F01%2F0001%2000%3A00%3A00&amp;PrimaryEmailFlag=False&amp;PrimaryEmailDate=01%2F01%2F0001%2000%3A00%3A00&amp;PrimaryEmailID=0&amp;PrimaryPhoneFlag=False&amp;PrimaryPhoneDate=01%2F01%2F0001%2000%3A00%3A00&amp;PrimaryPhoneID=0&amp;WifiConnected=False';" >Select customer</button>

As per my knowledge with @url.action we can only send route values and couldn't send the object itself.

Kindly refer this link: https://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action(v=vs.118).aspx

So for your problem, you can send any unique value to the controller action as a route parameter in url.helper and get the entire object from the database using linq query in action .

Note : if your requirement says that , you should send the object only, then you can put all the controls inside the form in the view and send it as post method.

Hope above information was helpful.

Thanks

Karthik

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