【问题标题】:Form Redirects before data is processed处理数据之前的表单重定向
【发布时间】:2019-08-10 16:04:10
【问题描述】:

我正在使用 EntityFramework(代码优先)模式制作 ASP.Net Core MVC。我有一个剃须刀页面,它使用所有表单输入呈现部分内容(删除了大部分易于阅读的 div)。这是 myPartial 在提交时调用我的控制器中的 AddClub 方法

    @using (Html.BeginForm("AddClub", "Club", FormMethod.Post, new { @class = "form-horizontal" }))
    {
        <div class="form-group">
            <label class="control-label col-sm-3">Club Sponser:</label>
            <div class="col-sm-4">
                @Html.TextBox("ClubSponser", null, new { @class = "form-control", id = "ClubSponser", placeholder = "Enter club Sponser" })
            </div>
        </div>
        <div class="btn-toolbar col-md-offset-7" role="group">
            <button type="submit" onsubmit="AddClub("ClubName","ClubOwner","ClubCoach","ClubSponser")" class="btn btn-primary">Add Club</button>
            <a href="@Url.Action("Index", "Home")" class="btn btn-danger">Cancel</a>
        </div>
    }

这是我的控制器 AddClub()

   [HttpPost]
    public ActionResult AddClub(string ClubName,string ClubOwner,string ClubCoach,string ClubSponser)
    {
        Club club = new Club()
        {
            Name = ClubName,
            Owner = ClubOwner,
            Coach=ClubCoach,
            Sponser=ClubSponser
        };
        clubRepo.AddClub(club);
        return RedirectToAction("Index","Club");
    }

这是我实现接口的服务类

   public async Task AddClub(Club club)
    {
        _context.Clubs.Add(club);
        await _context.SaveChangesAsync();
    }

启动服务被注入为单例

 services.AddSingleton<IClubRepo, ClubService>();

1) 我相信它正在发生,因为在我的服务中,Class 方法正在异步运行,这可能是原因(不确定)。我有这种预感,因为如果我不重定向它会完美地更新数据库

2) 我不想提出另一个问题,但我只想提出意见,如果这是在 ASP.Net core/MVC 中提交表单的正确方法

【问题讨论】:

    标签: asp.net-core model-view-controller ef-code-first


    【解决方案1】:

    您需要等待操作

    [HttpPost]
    public async Task<IActionResult> AddClub(string ClubName,string ClubOwner,string ClubCoach,string ClubSponser) {
        Club club = new Club() {
            Name = ClubName,
            Owner = ClubOwner,
            Coach=ClubCoach,
            Sponser=ClubSponser
        };
        await clubRepo.AddClub(club);
        return RedirectToAction("Index","Club");
    }
    

    为了让保存在重定向之前完成。

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 2011-02-26
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 2021-05-25
      • 1970-01-01
      相关资源
      最近更新 更多