将查询字符串传递给 mvc 视图操作

Pass Query string to mvc view action

当模型在 post 操作

中无效时,我想 return 与错误消息以及 query string 到同一页面

我的代码在这里

public ActionResult Action1(string Key)
{

    // do something
}

[HttpPost]
public ActionResult Action1(Model user)
{
    if (ModelState.IsValid)
                {
    // do some stuff here
    }
    else
     // redirect to same page with query string key and also error message
}

请通过显示错误消息建议我在模型无效时需要添加的行以留在同一页面中。

[HttpPost]
public ActionResult Action1(Model user)
{
    if (ModelState.IsValid)
    {
    // do some stuff here
    }
    else
    {
        return this.RedirectToAction ("Action1", new { value1 = "QueryStringValue" });
    }
}

那会 return 这个 :

/controller/Action1?value1=QueryStringValue

也根据您的评论。
您可以对模型使用以下方法,而不是将错误从控制器发送到视图以查看模型是否失败。

    [Required]
    [DataType(DataType.Text)]
    [StringLength(40)]
    public string FirstName { get; set; }

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

    [Required]
    [DataType(DataType.Password)]
    [StringLength(1000, MinimumLength = 8)]
    public string Password { get; set; }

    [Required]
    [System.Web.Mvc.Compare("Password")]
    [DataType(DataType.Password)]
    public string PasswordConfirmation { get; set; }
public ActionResult Action1(Model user)
{
    if (ModelState.IsValid)
    {
       // all is okay
    }
    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model);
}