(抱歉,如果所有这些问题都很愚蠢)
我的 Controller 中有两个方法
[HttpGet]
[Authorize]
public ActionResult Pokemon(int id)
{
var user = db.PDCUsers
.SingleOrDefault(x => x.Username == User.Identity.Name);
var pkmn = db.PlayerPkmns.SingleOrDefault(x => x.Id == id);
return View(new DetailedPokemonViewModel(pkmn, user.Id, user.StepsIncMult));
}
和
[HttpPost]
[ChildActionOnly]
[Authorize]
public ActionResult Pokemon(int id, int steps)
{
var user = db.PDCUsers.SingleOrDefault(x => x.Username == User.Identity.Name);
var pkmn = db.PlayerPkmns.SingleOrDefault(x => x.Id == id);
if (pkmn.CurrentTrainerId == user.Id)
{
pkmn.Experience = pkmn.Experience + steps;
db.SaveChanges();
}
return Pokemon(id);
}
我正在从 Pokemon(int id)
View 中调用 Pokemon(int id, int steps)
<a href="@Url.Action("Pokemon", "PokemonView", new { id = Model.Id, steps = 5000 })">walk</a>
但是,当我单击 Pokemon(int id, int steps)
的链接时,它不会更新数据库值 - 当我在其中放置断点时它也不会注册。我认为我什至没有点击该方法,但顶部的 url 连接了 steps 参数?
我要做的就是根据作为参数传递的步数来更新数据行的经验值。我不想要一个新 View (暂时)——我只希望它再次显示 Pokemon(int id) View 。
是否有调用方法然后返回调用它的 View 的最佳实践?另外,是否有任何明显的原因导致我的数据库值没有更新/断点没有被击中?
谢谢
编辑:
通过使用 RedirectToAction
而不是返回 Pokemon(int id)
方法,
并重命名 Pokemon(int id, int steps)
以避免重载 httpget 问题,它有效!
谢谢!
最佳答案
ChildActionOnly属性确保操作方法只能作为 View 中的子方法调用。所以你不需要使用[ChildActionOnly]
。您正在使用 a
转到链接,因此这是一个 GET
请求。
所以删除
[HttpPost]
[ChildActionOnly]
并更改您的返回声明,例如:
return RedirectToAction("Pokemon", new {id = id});
希望对你有所帮助。
关于c# - MVC ASP.NET 重载 Controller 方法无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44225243/