ASP.NET MVC Model Binding Related Entities on Same Page

蓝咒 提交于 2019-12-05 10:13:25

You might need to create a custom model binder for this?

Hopefully, I am understanding you problem correctly...

Rather than defining your Save action with 2 parameters, have you tried just defining it with a single parameter, of type Sku?

You would then want to redefine the item HTML controls similar to the following example...

<%=
    Html.TextBox
    (
        string.Format("sku.Items[{0}].{1}", i, "ItemId"), 
        Model.Items[i].ItemId, 
        new { @readonly = "readonly", onfocus = "this.blur();" }
    )
%>


This way, you're populating the items directly in the Sku object itself.


Another potential solution would be to add an additional field to your Item class, such as...

Int32 SkuId { get; set; }

This way, you could define an additional hidden field for each item in your view that would be auto-bound to the SkuId of each item back at the controller.

<%=
    Html.Hidden
    (
        string.Format("sku.Items[{0}].{1}", i, "SkuId"), 
        Model.Items[i].SkuId
    )
%>

You could then just update your items collection independently of your Sku object. Regardless of which way you go, the two collections have to explicitly tell Linq to SQL to update the sku and items anyhow.

You could also define your own binder class, but that's probably more work than it's worth in this case. Just follow the ASP.NET MVC conventions, and I think you should be able to find something that will work without feeling like it's a hack.

I had a similar issue where EntitySets weren't bound properly in my ViewModel.

What I did was to create another property called Mvc[YourEntitySetPropertyName], as a generic list, that wrapped around the private fields of the EntitySet:

public List<InvoiceLineItem> MvcInvoiceLineItemList
    {
        get { return _invoiceLineItemList.ToList(); }
        set { _invoiceLineItemList.AddRange(value); }
    }

I then used that instead of the EntitySet property on my view markup.

There will be no need to pass the items in your controller method signature- just pass the Sku at that point:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Sku sku)
{
    if (sku != null)
    {
       // save Sku to repository ...
       // return Details view ...
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!