我在尝试使自定义POST请求生效时遇到问题。
到目前为止,我已经尝试了几种可能的解决方案,例如弄乱了路由,使用了表单和asp标签助手等,但是我无法查明问题所在。
请参阅下面附上的代码,在提交表单时,我希望将使用提供的适当To和From值作为输入来调用OnPostAdd方法。但是,该页面仅重定向到“ ./ContextFreeGrammar/Add”,而无需执行发布请求。
OnGet()和OnPost()在此页面模型中有效,但是如何调用AddRule(Rule规则)?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Earley_Parser.Language;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Http;
namespace Storyteller.Pages.EarleyParser {
public class ContextFreeGrammarModel : PageModel {
public readonly Grammar_2 _grammarContext;
public ContextFreeGrammarModel(IGrammar grammarContext) {
_grammarContext = (Grammar_2) grammarContext;
_grammarContext.Add("", "S");
_grammarContext.Add("A", "S");
_grammarContext.Add("AA", "A");
_grammarContext.Add("a", "A");
}
// POST: Default/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult OnPostAdd(String to, String from) {
try {
// TODO: Add insert logic here
_grammarContext.Add(to, from);
return RedirectToPage();
} catch {
return Page();
}
}
// POST: Default/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult OnPostDelete(Int32 id) {
try {
// TODO: Add delete logic here
_grammarContext.Remove(_grammarContext.ElementAt(id));
return RedirectToPage();
} catch {
return Page();
}
}
}
}
@page
@model Storyteller.Pages.EarleyParser.ContextFreeGrammarModel
@section Scripts {
<script>
$(function () {
// jQuery methods go here...
$("#F").keyup(function () {
if (this.value.length == this.maxLength) {
$("#T").focus();
}
});
});
</script>
}
<div>
<form asp-action="add" method="post">
<table id="grammarRuleTable" class="table">
<tbody>
@foreach (var rule in Model._grammarContext) {
<tr>
<td style="text-align:center" class="oneCharacterWideColumn">
@(new String(rule.f))
</td>
<td class="oneCharacterWideColumn">
→
</td>
<td style="margin:0">
@(new String(rule.t))
</td>
<td class="oneCharacterWideColumn">
<button onclick="myFunction()">
<i class="material-icons">delete_forever</i>
</button>
</td>
</tr>
}
<tr>
<td class="oneCharacterWideColumn">
<input id="F" type="text" maxlength="1" size="1" style="text-align:center"
asp-route-to="from" />
</td>
<td class="oneCharacterWideColumn" width="">
→
</td>
<td>
<input id="T" type="text" maxlength="128" style="width:100%"
asp-route-to="to" />
</td>
<td class="oneCharacterWideColumn"></td>
</tr>
</tbody>
</table>
</form>
</div>
答案 0 :(得分:0)
您可以通过处理程序执行此操作。
public IActionResult OnPostAdd(String to, String from) {
try {
// TODO: Add insert logic here
_grammarContext.Add(to, from);
return RedirectToPage();
} catch {
return Page();
}
}
-
<form asp-page-handler="Add" method="POST">
<button type="submit" class="btn btn-default">Add Grammar</button>
<input id="handler_parameter_from" type="hidden" name="from" value="hello"/>
<input id="handler_parameter_to" type="hidden" name="to" value="world"/>
</form>
请注意名称OnPost Handler 或OnPost Handler 异步。
您甚至可以使用Multiple handlers per page