Как мне запросить сервер добавить элемент в коллекцию? - PullRequest
1 голос
/ 24 апреля 2019

У меня проблемы с попыткой заставить работать пользовательские запросы POST.

Я уже пробовал пару возможных решений, например, возиться с маршрутизацией, использовать формы и помощники тегов asp и т. Д., Но я не смог точно определить проблему.

Ссылаясь на код, приложенный ниже, при отправке формы я ожидаю, что метод OnPostAdd будет вызываться с соответствующими значениями To и From, предоставленными в качестве входных данных.Однако страница просто перенаправляется в «./ContextFreeGrammar/Add» без выполнения запроса на публикацию.

OnGet () и OnPost () работают в этой модели страницы, но как мне получить AddRule (правило правила), чтобыназывается?

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>

1 Ответ

0 голосов
/ 24 апреля 2019

Вы можете сделать это с обработчиками.

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 Async.

Вы даже можете использовать Несколько обработчиков на страницу

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...