Форма не отправляется при клике - PullRequest
0 голосов
/ 21 октября 2019

Я пытаюсь добавить «Create» на один из моих контроллеров (LeagueController), поэтому я создал Create View, который использует мой League объект.

Однако, когда я иду, чтобы отправить форму, она не перенаправляет обратно в представление Index, как я этого хочу, и при этом не вводит запись журнала, чтобы сообщить, что я создал лигу.

League Класс

public class League : BaseEntity
{
    [Required]
    [DataType(DataType.Text)]
    public string LeagueName { get; set; }

    [Required]
    [DataType(DataType.Text)]
    public string LeagueInitials { get; set; }

    [DataType(DataType.Text)]
    public string LeagueURL { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime Founded { get; set; }

    [InverseProperty("League")]
    public ICollection<Team> Teams { get; set; }

    [ForeignKey("LeagueID")]
    public ICollection<LeagueOwners> LeagueOwners { get; set; }
}

LeaguesController Класс

public class LeaguesController : Controller
{
    private MyDBContext context;
    private ILogger logger;

    public LeaguesController(MyDBContext context, ILogger logger)
    {
        this.context = context;
        this.logger = logger;
    }

    public IActionResult Index()
    {
        this.logger.LogInformation("Reached League Index");
        return View();
    }

    [Route("Create")]
    public IActionResult Create()
    {
        this.logger.LogInformation("Creating a league");
        return View();
    }

    [HttpPost]
    public IActionResult Create(League league)
    {
        this.logger.LogInformation("Create button clicked!");
        return this.RedirectToAction("Index");
    }
}

Create.cshtml

@model MySite.Core.Entities.League

@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

<h4>League</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="LeagueName" class="control-label"></label>
                <input asp-for="LeagueName" class="form-control" />
                <span asp-validation-for="LeagueName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="LeagueInitials" class="control-label"></label>
                <input asp-for="LeagueInitials" class="form-control" />
                <span asp-validation-for="LeagueInitials" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="LeagueURL" class="control-label"></label>
                <input asp-for="LeagueURL" class="form-control" />
                <span asp-validation-for="LeagueURL" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Founded" class="control-label"></label>
                <input asp-for="Founded" class="form-control" />
                <span asp-validation-for="Founded" class="text-danger"></span>
            </div>
            <div class="form-group" hidden="hidden">
                <label asp-for="Created" class="control-label"></label>
                <input asp-for="Created" class="form-control" value="@DateTime.Now" />
                <span asp-validation-for="Created" class="text-danger"></span>
            </div>
            <div class="form-group" hidden="hidden">
                <label asp-for="Modified" class="control-label"></label>
                <input asp-for="Modified" class="form-control" value="@DateTime.Now" />
                <span asp-validation-for="Modified" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

Ответы [ 2 ]

1 голос
/ 22 октября 2019

Первый способ заключается в том, что вы можете удалить [Route("Create")], который используется в вашем методе get.

Второй способ заключается в том, что вы можете добавить атрибут [Route] в свой метод записи, как показано ниже:

[Route("Create")]
public IActionResult Create()
{
    this.logger.LogInformation("Creating a league");
    return View();
}
[Route("Create")]
[HttpPost]
public IActionResult Create(League league)
{
    this.logger.LogInformation("Create button clicked!");
    return this.RedirectToAction("Index");
}
1 голос
/ 21 октября 2019

В вашей форме <form asp-action="Create" method="post"> добавьте тег, указывающий на правильный контроллер asp-controller="Leagues"

Не применяйте маршрут, это просто анти-шаблон.

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