问题
So I am trying to post a view with a model that contains a list of models, but when posting, only the first model in the list of models show their Id. I am using the editorFor to show my models through the editor template. Notice in the template I have the hiddenFor for the Id value. Why when i post the form it only shows the first model in the list? How do I fix this so that the post will contain all the Id values in the list of models being posted? Its able to post the values for the drop downs somehow for all of them.
Main View:
@using (Html.BeginForm("OrderPost", "Order", FormMethod.Post))
{
<table id="orders">
<thead>
<tr>
<th>
</th>
<th>
<b>ID</b>
</th>
<th>
<b>Product Name</b>
</th>
<th>
<b>SKU</b>
</th>
<th>
<b>Quantity</b>
</th>
<th>
<b>Price</b>
</th>
<th>
<b>Sub Total</b>
</th>
</tr>
</thead>
@Html.EditorFor(x => x.LineItemModels)
</table>
<button type="submit"> submit</button>
}
Editor Template:
@model Project.Models.LineItemModel
@Html.HiddenFor(x => x.Id)
<tr>
<td>
@if (!Model.HideSelected) {
@Html.CheckBoxFor(x => x.Selected)
}
else
{
<span>Returned</span>
}
</td>
<td>
@Model.Id
</td>
<td>
@Model.Name
</td>
<td>
@Model.SKU
</td>
<td>
@if (!Model.HideSelected) {
@Html.DropDownListFor(x=>x.QuantitySelected, Model.QuantityToRefund)
}
else
{
<span>0</span>
}
</td>
<td id="subTotal @Model.Id" class="subTotal"></td>
</tr>
Model:
public class OrderModel
{
public List<LineItemModel> LineItemModels { get; set; }
public string Comments { get; set; }
public int OrderId { get; set; }
}
![enter image description here][1]
(tried to post image of debug mode of the Id only showing in Model[0] but i need a rep of 10 i guess...)
回答1:
I think that you can use JSON format (using JSON.stringify()) to post data to the server, with JQuery you can build your array
var model = {};
model.field1 = $('#field1').val();
model.field2 = $('#field2').val();
model.field3 = ...
var _data = {};
_data.OrderId = 100;
_data.Comments = 'Some comments';
_data.LineItemModels = BuildArray(); //BuildArray return an array of model objects in your form that most have the LineItemModel structure
$.ajax({
url: yourUrl,
type: "POST",
cache: false,
data: JSON.stringify(_data),
dataType: "json",
contentType: 'application/json',
success: function (data) {},
error: function (request) {}
});
来源:https://stackoverflow.com/questions/23158001/posting-a-list-of-view-models-in-a-model-in-asp-net-mvc-4