【发布时间】:2020-11-14 07:26:54
【问题描述】:
我有两张表,一张是一对一或一对零的关系:
public class ComponentText
{
[Key]
public int ComponentTextId { get; set; }
public string ComponentContent { get; set; }
public ComponentTextSection ComponentTextSection { get; set; }
}
public class ComponentTextSection
{
[Key]
public int ComponentTextId { get; set; }
public string SectionTitle { get; set; }
public ComponentText ComponentText { get; set; }
}
我可以使用通常的 .net 核心发布使用表单添加行,这是执行此操作的代码:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var newComponentText = new ComponentText();
if (await TryUpdateModelAsync<ComponentText>(
newComponentText,
"ComponentText",
i => i.ComponentTextSection, i => i.ComponentContent))
{
_context.ComponentText.Add(newComponentText);
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
我需要通过 ajax 进行更新,但我在使用这种当前方式更新 SectionTitle 时遇到了问题。它将数据添加到 ComponentText 表中,但不是 ComponentTextSection 表。这是我的ajax代码:
function saveWindow() {
var ComponentText = { "ComponentText.ComponentTextSection.SectionTitle": $("#ComponentText_ComponentTextSection_SectionTitle").val(),
"ComponentTextId": $("#ComponentText_ComponentTextId").val(),
"ComponentContent": $("#ComponentText_ComponentContent").val()};
$.ajax({
type: 'PUT',
contentType: 'application/json; charset=utf-8',
headers: {
'RequestVerificationToken': '@AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'
},
data: JSON.stringify(ComponentText),
url: '@Url.Page("Edit", "demo4")',
success: function (result) {
closeWindow();
}
});
}
这一定与 ComponentText.ComponentTextSection.SectionTitle 有关,但我一直在尝试很多事情来让它工作但失败了。有谁知道如何通过 ajax 传递一对一的相关数据?
谢谢
【问题讨论】:
标签: ajax asp.net-core .net-core entity-framework-core razor-pages