简体   繁体   English

MVC模型绑定复杂类型到操作参数

[英]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. 我正在使用MVC3的模型绑定将客户列表绑定到客户搜索结果页面,并使用Razor在foreach循环中呈现所有客户。 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. Customer对象非常大,即。 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. @ URL.Action呈现的html如下所示,看起来是一个好的开始,但只有一些客户字段,而不是全部。 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. 根据我对@ url.action的了解,我们只能发送路由值而无法发送对象本身。

Kindly refer this link: https://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action(v=vs.118).aspx 请参考此链接: 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 . 因此,对于您的问题,您可以将任何唯一值作为url.helper中的路由参数发送到控制器操作,并使用linq查询操作从数据库中获取整个对象。

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. 注意:如果您的要求说明了,您应该只发送对象,然后您可以将表单中的所有控件放在视图中并以post方式发送。

Hope above information was helpful. 希望以上信息是有帮助的。

Thanks 谢谢

Karthik KARTHIK

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

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