【问题标题】:Pass Query string to mvc view action将查询字符串传递给 mvc 视图操作
【发布时间】:2015-11-02 11:26:11
【问题描述】:

当模型在后期操作中无效时,我想返回同一页面并显示错误消息以及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
}

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

【问题讨论】:

标签: c# asp.net-mvc model-view-controller razor query-string


【解决方案1】:
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);
}

【讨论】:

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

    这将返回:

    /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; }
    

    【讨论】:

    • 但是这里没有显示错误信息,这等于RedirectToAction(),我需要view()
    • 对不起,我没有得到你。没有收到错误消息是什么意思?
    • 如果模型无效,我会显示一些错误信息,例如长度应该大于6或密码和确认密码不匹配,它不显示
    猜你喜欢
    • 1970-01-01
    • 2019-07-02
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 2012-02-25
    • 1970-01-01
    • 2013-06-13
    相关资源
    最近更新 更多