2015-11-02 35 views
1

我想query string隨着錯誤消息以返回到相同頁面時的模型在術後無效通查詢字符串MVC視圖操作

我的代碼是在這裏

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 
} 

請建議行我需要添加模型無效時通過顯示錯誤消息保持在同一頁面。

+1

[這可以幫助你(http://benfoster.io/blog/aspnet-mvc-custom-error-pages) – hellogoodnight

回答

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; } 
+0

但這裏的錯誤信息沒有顯示,這等於RedirectToAction(),我需要view() –

+0

對不起,我沒有得到你。你沒有收到錯誤信息是什麼意思? –

+0

如果模型是無效的,我可以顯示一些錯誤消息,如長度應該超過6或密碼和確認密碼不匹配,它不顯示 –

2
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); 
}