我正在使用EntityFramework(代码优先)模式制作ASP.Net核心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>
}
这是我的Controller 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();
}
在启动服务中注入Singleton
services.AddSingleton<IClubRepo, ClubService>();
1)我相信它正在发生,因为在我的服务类方法是异步运行可能是原因(不确定)。我有这种预感,因为如果我不重定向它完全更新数据库
2)我不想提出另一个问题,但我只是想要一个意见,如果这是在ASP.Net core / MVC中提交表单的正确方法
你需要等待行动
[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");
}
为了在重定向之前允许保存完成。