Losing complete Model when posting Ajax values to controller

136 views Asked by At

What i want to do is have 2 listboxes (left, right) where left would have all products entities except the ones that are present in my Contract Entity and in the right the products in my Contract Entity.

I am having this issue that when i pass 1 parameter (string) I can receive them correctly in my controller but whenever i pass my model with it as a second parameter i loose my model completely. This is what i have:

Controller:

public ActionResult EditContract(ContractViewModel model, string selectedProducts)

View (Javascript/JQuery):

  function GetSelectedProducts() {

        var listbox = document.getElementById("productsForContractListbox");
        var txt = "";
        var i;

        for (i = 0; i < listbox.length; i++) {
            txt = txt + "\n" + listbox.options[i].text;
        }

        $('#SelectedProductForContracts').val(txt);
        var selectedProducts = $('#SelectedProductForContracts').val();

        var model = $('form').serialize;

        $.post('@Url.Action("EditContract", "Contract")', { "model": model, "selectedProducts": selectedProducts});
    }           

Html helper listboxes:

// listbox for my contract products
@Html.ListBoxFor(c => c.Contract.Products, productsForContract, new { ID = "productsForContractListbox", @class = "form-control" })

// listbox where all products except the ones in my contract are loaded
@Html.ListBox("allProducts", allProducts, new { ID = "allProductsListbox", @class = "form-control" })

HiddenFor for the SelectedProductForContracts from my Model:

@Html.HiddenFor(c => c.SelectedProductForContracts, new { ID = "SelectedProductForContracts", name = "SelectedProductForContracts" })

Model:

[HiddenInput(DisplayValue = false)]
public List<SelectListItem> SelectedProductForContracts { get; set; }

When having the post data containing only the selectedProducts, i get my values but lose my model, when i add my model i get my model but lose my selectedProducts values.

I tried several things like THIS but couldn't get them to work in my case (i am doing something wrong probably but don't know what ...)

Can anyone help me towards the proper way of achieving this cause i see many ways but i hope there must be an elegant way of binding everything to 1 model without having to use javascript/Jquery ?

Kind regards!

1

There are 1 answers

3
Richard Hubley On BEST ANSWER

List<SelectListItem> is not able to be defined in a single hidden variable