如何在Mvc4
中使用Ajax表单从视图向控制器发送数据列表:
我的模型示例:
public class Food
{
public string name { get; set; }
public int quantity { get; set; }
}
public class CustomerModel {
public string CustomerName { get; set; }
public List<Food> ListFoods { get; set; }
}
[HttpPost]
public ActionResult AddCustomer(CustomerModel model)
{
//Add New Person
return Json(new { Result = "OK" });
}
我的查看:
@using (Ajax.BeginForm("AddCustomer", "Resturant", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "Success"
}, new { @id = "frmaddCustomer" }))
{
<p>
<label>Customer Name </label>
</p>
<p>
@Html.CH_TextBox("CustomerName").size(TextBoxSize.Medium)
</p>
<p>
Food List
</p>
<table id="FoodList" class="static-table" data-bind='visible: gifts().length > 0'>
<thead>
<tr>
<td style="width: 250px;">Name</td>
<td>Quantity</td>
<td />
</tr>
</thead>
<tbody data-bind='foreach: gifts'>
<tr>
<td>
@Html.CH_TextBox("Food.name").size(TextBoxSize.Medium)
</td>
<td>
@Html.CH_TextBox("Food.quantity").size(TextBoxSize.Medium)
<td>
<a id="deleteRow">Delete</a>
</tr>
</tbody>
</table>
<button data-bind='click: addGift' type="submit">New Food</button>
<button data-bind='enable: gifts().length > 0' type="submit">Send Data</button>
}
答案 0 :(得分:1)
我使用以下方法将数据发布到控制器模型:
<tr>
<td>
@Html.CH_TextBox("Food[0].name").size(TextBoxSize.Medium)
</td>
<td>
@Html.CH_TextBox("Food[0].quantity").size(TextBoxSize.Medium)
</td>
<td>
<a id="deleteRow">Delete</a>
</td>
</tr>
<tr>
<td>
@Html.CH_TextBox("Food[1].name").size(TextBoxSize.Medium)
</td>
<td>
@Html.CH_TextBox("Food[1].quantity").size(TextBoxSize.Medium)
</td>
<td>
<a id="deleteRow">Delete</a>
</td>
</tr>
<tr>
<td>
@Html.CH_TextBox("Food[2].name").size(TextBoxSize.Medium)
</td>
<td>
@Html.CH_TextBox("Food[2].quantity").size(TextBoxSize.Medium)
</td>
<td>
<a id="deleteRow">Delete</a>
</td>
</tr>
通过使用这种方法,我的问题得到了解决。 谢谢。