【发布时间】:2019-10-10 10:42:08
【问题描述】:
编辑:已标记原始代码中的错误导致其无法正常工作的位置。
我可以在 MVC 上找到大量相关信息和示例,但似乎不适用于 Razor Pages?
简单场景:我有一个页面 (FooList) 显示 Foo 项目的列表。每个都有一个编辑按钮。这将打开一个模式弹出窗口,其中的布局(和数据)来自第二页 (FooEdit)。
Edit 表单出现并且填充得很好,但我不知道如何让它将数据发布回后面的 FooEdit 代码?
列表页,FooList.cshtml
@page
@model Pages.FooListModel
<table>
@foreach (var item in Model.FooListVM)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a onclick="openModal(@item.ID);">Edit</a>
</td>
</tr>
}
</table>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header border-bottom-0">
<h5 class="modal-title" id="exampleModalLabel">Edit Foo</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form> <---- Edit: ** This shouldn't be here **
<div class="modal-body">
</div>
</form> <---- Edit
</div>
</div>
</div>
<script>
function openModal(i) {
$.get("FooEdit?id="+i,
null,
data => {
$("#editModal").modal("show");
$("#editModal .modal-body").html(data);
});
};
</script>
后面的代码,FooList.cshtml.cs
public class FooListModel : PageModel
{
public IList<FooListVM> FooListVM { get; set; }
public void OnGet()
{
FooListVM = new List<FooListVM>
{
new FooListVM { ID = 1, Name = "Foo 1" },
new FooListVM { ID = 2, Name = "Foo2" }
};
}
}
public class FooListVM
{
public int ID { get; set; }
public string Name { get; set; }
}
弹出窗口的第二页,FooEdit.cshtml
@page
@model Pages.FooEditModel
@(Layout=null)
<form method="post">
<input asp-for="FooEditVM.Name" class="form-control" /><br />
<input asp-for="FooEditVM.Stuff1" class="form-control" /><br />
<input asp-for="FooEditVM.Stuff2" class="form-control" /><br />
<input type="submit" value="Save"/>
</form>
以及弹出窗口背后的代码 FooEdit.cshtml.cs
public class FooEditModel : PageModel
{
[BindProperty]
public FooEditVM FooEditVM { get; set; }
public void OnGet(int id)
{
FooEditVM = new FooEditVM
{
Name = $"This is item {id}",
Stuff1 = "Stuff1",
Stuff2 = "Stuff2"
};
}
public void OnPost(int id)
{
// How do we get to here???
var a = FooEditVM.Name;
}
}
public class FooEditVM
{
public string Name { get; set; }
public string Stuff1 { get; set; }
public string Stuff2 { get; set; }
}
我已经阅读了有关 Asp.net Core 2.2 的所有 MS 教程,但似乎没有涵盖这一点。
还有一个附带的问题,虽然它有效,但是否有一种“ASP 辅助标签”方式来处理 ajax 位?
【问题讨论】:
标签: ajax post asp.net-core-2.0 razor-pages