简体   繁体   English

如何在提交表单发布方法之前将复杂数据类型附加到视图模型

[英]How to append Complex Data Type to View Model before submit of form post method

I am using Form Post method to submit data to controller in my MVC application. 我正在使用Form Post方法将数据提交到MVC应用程序中的控制器。 My MVC Application controller method accepting ViewModel. 我的MVC应用程序控制器方法接受ViewModel。 I have added new list of other viewModel and I want to pass the data to that newly added viewmodel. 我添加了其他viewModel的新列表,我想将数据传递给该新添加的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 JavaScript代码

    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. 您将获得两个记录的列表作为(0和1)索引。

You can use for loop and generate hidden html dynamically and append it before Form submit. 您可以使用for循环并动态生成隐藏的html,然后将其附加在Form提交之前。

you need to define the list as property inside the ViewModel you are passing, by default modelbinder does not consider the fields like 您需要将列表定义为要传递的ViewModel内的属性,默认情况下,modelbinder不考虑诸如

Branch_Product_Taxes = new List<Branch_Product_TaxesViewModel>();

you need to define the property Like 您需要定义属性Like

 public IList<Branch_Product_TaxesViewModel> Branch_Product_Taxes  { get; set; }

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

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