问题描述:

I am using Form Post method to submit data to controller in my MVC application.

My MVC Application controller method accepting ViewModel.

I have added new list of other viewModel and I want to pass the data to that newly added viewmodel.

Sample Code ( not fully executed )

Controller Existing Code

public ActionResult AddProduct(ProductViewModel productViewModel)

{

//some operation

}

public class ProductViewModel

{

Branch_Product_Taxes = new List<Branch_Product_TaxesViewModel>();

}

//viewmodel

$('#ProductForm').submit(); //javascript form submit method

var ObjectList = new Array()

Now I have added List of Objects in Object List

I want to pass this list controller

网友答案:

You need to create hidden elements as per your complex data type Consider following issue If you need to post employee list with attribute like name etc then go through following code.

Your view Model something like

 public class ProductViewModel
{
     public IList<Employees> = new List<Employees>();
} 

Javascript Code

    var  html = '<input type="hidden" name="Employees[0].Name" value="Employee1"/>';
    html+='<input type="hidden" name="Employees[0].Designation" value="Des1"/>';
    html+='<input type="hidden" name="Employees[1].Name" value="Employee2"/>';
    html+='<input type="hidden" name="Employees[1].Designation" value="Des2"/>';
    $('#ProductForm').append(html);
    $('#ProductForm').submit();

You will get list of two records as (0 and 1 ) index.

You can use for loop and generate hidden html dynamically and append it before Form submit.

网友答案:

you need to define the list as property inside the ViewModel you are passing, by default modelbinder does not consider the fields like

Branch_Product_Taxes = new List<Branch_Product_TaxesViewModel>();

you need to define the property Like

 public IList<Branch_Product_TaxesViewModel> Branch_Product_Taxes  { get; set; }
相关阅读:
Top