【发布时间】:2018-12-28 11:25:53
【问题描述】:
在我显示书籍列表的页面中,有一个“添加新书”按钮,如果用户单击,我希望将一个项目添加到列表中,它可以工作。
但是如果用户点击“提交”按钮,在控制器中,我在代码中创建了刚刚发布的 2 本书
查看:
@model WebApplication2.Models.Book2
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-right">
<input type="button" onclick="@Url.Action("PlaceOrder")" value="Add Product" class="btn btn-primary" />
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<table class="table table-condensed table-hover">
<tbody id="books">
<tr>
<th>
Product Code
</th>
<th>
Product Name
</th>
</tr>
@{
int i = 0;
foreach (var item in Model.Books.ToList())
{
<tr>
<td>
@Html.EditorFor(o => o.Books[i].Author, new { @id = "Author_" + i })
</td>
<td>
@Html.EditorFor(o => o.Books[i].Title, new { @id = "Title_" + i })
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
i++;
}
}
</tbody>
</table>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-center">
<input type="button" id="addbook2" name="addbook" value="Add New Book" />
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</div>
</div>
@section Scripts {
<script type="text/javascript">
$("#addbook2").on('click', function () {
$.ajax({
async: false,
url: '/Book/CreateNewBook',
success: function (partialView) {
console.log("success");
$('#books').append(partialView);
}
})
});
</script>
}
}
控制器代码:
public class BookController : Controller
{
public ActionResult Index()
{
Book[] books = new Book[]
{
new Book()
{
ID = 1, Title = "title01", Author = "author01",
},
new Book()
{
ID = 2, Title = "title02", Author = "author02",
},
};
return View(new BooksContainer()
{
Books = books.ToList(),
});
}
[HttpPost]
public ActionResult Index(BooksContainer books)
{
// books.Books.Count is 2! why?
return View();
}
public ActionResult CreateNewBook()
{
var book = new Book()
{
ID = new Random().Next(3, 999_999),
};
return PartialView("~/Views/Shared/createBook.cshtml", book);
}
}
CreateBook 部分视图:
@model WebApplication2.Models.Book
<tr>
<td>
@Html.EditorFor(o => o.Author, new { @id = "Author_" + Model.ID })
</td>
<td>
@Html.EditorFor(o => o.Title, new { @id = "Title_" + Model.ID })
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
@Html.ActionLink("Details", "Details", new { id = Model.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = Model.ID })
</td>
</tr>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
为什么后控制器中的书籍数量为 2,而我看不到添加的书籍。
如果我在提交后手动将第三个<tr> 输入的名称设置为Books[2].Author 和Books[2].Title,在控制器中我可以看到3 本书。如何解决这个问题?
【问题讨论】:
-
我认为您需要的是 Book 模型的编辑器模板,然后在您的 foreach 循环中使用
EditorFor(o => o.Books[i])。
标签: c# asp.net asp.net-mvc html-table