MVC 下一步按钮功能



我是MVC的新手,我仍然有WPF的心态。我有一个控制器,它返回一个以 ID 作为参数的模型。

我想通过按剃须刀视图中的按钮来增加该参数,并重新加载具有该新 ID 的另一个模型。

我尝试过类似的东西:

    public ActionResult Game() {        
        SequenceViewModel model = new SequenceViewModel(CardModelList, SelectedSequenceID);
        return View(model);
    }

并在该按钮上执行另一个操作:

   public ActionResult Press()
    {
        SelectedSequenceID ++;         
       return RedirectToAction("Game", "Game");
    }

即使我的 SelectedSequenceID 接缝设置为正常,模型仍然具有旧值。

我的方法完全错误吗?

谢谢尤利亚

您不想在控制器中增加 ID,只需在视图中有一个指向下一个 ID 的链接即可!

MVC 比 Web 表单更接近 HTTP 理想,并且 HTTP 是无状态的,因此您需要假设状态不会在页面请求周期之间保留(好吧,您可以使用会话、cookie 等来执行此操作,但只保留绝对必要的内容!

请记住,默认路由将从 URL/controller/action/id 中获取参数"id",因此示例控制器可能如下所示

public class GamesController : Controller
{
  // eg. /Games/Game/1
  public ActionResult Game(int id){
    var SequenceModel = SequenceRepository.GetSequenceById(id); //some way of getting your model from the ID
    return View(SequenceModel);
  }
}

在视图中,您需要添加链接才能导航

@Html.ActionLink("Next", "Game", new {@id = Model.id + 1})

或作为按钮:

<input type="button" value="Next" onclick="@Html.Raw("location.href='" + Url.Action("Next", new {@id = Model.id + 1}) + "';")" />

有很多方法,但其中一种可能是这样的:

[HttpPost]
public ActionResult Press(string nextStep)
{
    // not sure what this functionality does...
    //SelectedSequenceID ++;         
    //return RedirectToAction("Game", "Game");
    switch (step)
    {
        case "Intro":
            // call method to run intro method or redirect to intro action
            break;
        default:
            // return to start
            break;
    }
}

然后,将其放入具有相应名称的剃须刀视图中:

<input type="submit" name="submitButton" value="Intro" />

最新更新