[英]How to keep track of a certain ID while switching through different views in ASP.NET Core?
[英]How do I keep track of related record ID's in ASP.Net core for updating child records
我是 asp.net 內核的新手和初學者。 我正在創建一個應用程序,該應用程序需要一個更新項目的頁面,並且它是同一頁面上的子項目。 更新父數據很容易,但我對如何更新子項目有點迷茫。
這是項目和子項目的簡化 model:
public class Test
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<TestChild> TestChildren { get; set; }
}
public class TestChild
{
public int ID { get;set; }
public string ChildName { get;set; }
public int TestID { get;set; }
public Test Test {get; set; }
}
我使用與此類似的代碼在 Razor web 頁面上將其呈現給用戶:
...
<input asp-for="Test.Name" class="form-control" />
@foreach (var child in Model.Test.TestChildren)
{
<input name="TC.@child.ID" value="@child.ChildName">
}
...
我的計划是使用子輸入框中的名稱字段來返回每個子記錄的 ID,這與值字段一起可以讓我更新正確的記錄。 這意味着當表單發布時,返回的數據可能類似於以下內容:
TC.4 = "Child 1"
TC.6 = "Child 2"
TC.9 = "Child 3"
其中.X 是相關子項的 ID,名稱是它的新/更新名稱。 我真正想要的是以某種方式返回一個字典,其中鍵是 ID,值是名稱。
但是,如果我在發布表單時使用上面的代碼,我不知道將變量聲明為什么類型,它會按照以下方式傳遞給 onpost function:
public async Task<IactionResult> OnPostAsync(int id, ???????????)
{
...
What variable type should I use to map to the data above?
}
所以我的問題是:
謝謝你的幫助
我不認為這是最好的方法。
您不需要在 post 方法中添加接收參數。 因為你將Test
數據傳遞到頁面,你的代碼后面應該有一個Test
類型的字段,對吧?
您只需確保在提交視圖時 model 是Test
類型。 您需要確保the name of children is consistent with the hierarchical relationship of the model
。
並且您需要add the ID field as a hidden field
,以確認您正在更新哪些數據。
這是代碼:
public class IndexModel : PageModel
{
private readonly MydbContext _context;
public IndexModel (MydbContext context)
{
_context = context;
}
[BindProperty]
public Test Test { get; set; }
public void OnGet()
{
// here is an example to pass data to view.
Test = _context.Test.Include(x => x.TestChildren).Where(x => x.ID == 5).FirstOrDefault();
}
public async Task<IActionResult> OnPostAsync()
{
//the Test parameter will change which is contains the value you changed.
var newtest = _context.Test.Include(x => x.TestChildren).Where(x => x.ID == Test.ID).FirstOrDefault();
newtest.Name = Test.Name;
newtest.TestChildren = Test.TestChildren;
_context.SaveChanges();
return Page();
}
}
看法:
@page
@model WebApplication1_razor_page.IndexModel
@{
ViewData["Title"] = "TestChild";
Layout = "~/Pages/Shared/_Layout.cshtml";
var i = 0;
}
<h1>Index</h1>
<form method="post">
<input asp-for="Test.ID" class="form-control" hidden />
<input asp-for="Test.Name" class="form-control" />
@foreach (var child in Model.Test.TestChildren)
{
<input asp-for="@child.ID" name="Test.TestChildren[@i].ID" hidden/>
<input asp-for="@child.ChildName" name="Test.TestChildren[@i].ChildName" />
i++;
}
<input id="Submit1" type="submit" value="update" />
</form>
這是測試結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.