2017-09-06 49 views
-5

我在使用ASP.net mvc中的錯誤消息的問題。當用戶點擊保存即使沒有輸入任何內容時,仍然會將它們重定向到另一個頁面,但是如果沒有輸入任何信息,我想給他們一個錯誤信息。我希望它在客戶端完成。這是我有迄今添加錯誤消息按鈕點擊在Asp.net Mvc

[HttpPost] 
    public ActionResult Finish(Student model, string finish) 
    { 
     if (!ModelState.IsValid) 
     { 
      ViewBag.error("No item was entered"); 
      return View(getStudent); 
     } 

     else (string.IsNullOrEmpty(finish)) 
     { 
      //redirects to student record page when finish is clicked 
      return RedirectToAction("StudentRecord"); 
     } 

    } 

凡在這裏會把錯誤消息

<div class="col-md-offset-4 col-md-12"> <input type="button" value="Finish" name="Issue" margin="50px" onclick="location.href='@Url.Action("ViewIssue","Issue")' " class="btn btn-default" /> </div> 
+1

您可以添加標記 – Izzy

+0

你能不能給學生上課? – Win

+0

你應該在'Student'模型上使用'DataAttributes'並讓asp.net爲你處理驗證。 –

回答

0

設置你的視圖顯示TempData的,其工作原理相同的ViewBag,而是通過重定向堅持其數據,以防你的Model.IsValid條件失敗。另外,在if條件中加入一個try/catch語句以防萬一。 此外,我建議您返回到您的原始視圖,以防用戶填寫表單錯誤,以便他可以修復它。

操作:

[HttpPost] 
public ActionResult Finish([Bind(Include = "propertyName1,propertyName2,propertyName3")] Student model, string finish) 
{ 
    if (ModelState.IsValid) 
    { 
     try { 
      //do your logic here 
      return RedirectToAction("StudentRecord"); 
     } catch (Exception ex) { 
      TempData["errorMessage"] = "Error: " + ex.Message + " - " + ex.InnerException; 
      //ViewBag.errorMessage = "Error: " + ex.Message + " - " + ex.InnerException; 
      return View(model); 
     } 
    } 
    else 
    { 
     TempData["errorMessage"] = "Error: Please fill the form correctly"; 
     return View(model); 
    } 
} 

然後在您的視圖:

@model your_domain.Student 

<span> 
    @TempData["errorMessage"] 
    //@ViewBag.errorMessage 
</span> 
+0

我試過這個解決方案,但我似乎沒有得到一個輸出它只是重定向到其他頁面 –

+0

@bujulloyd請注意,該行動應該做只有當ModelState有效時,纔有任何邏輯。我顛倒了原來的邏輯順序並設置了其他的,也就是當ModelState不適合存儲錯誤消息時,它將在稍後顯示在視圖中。 – Tiramonium

+0

@ bujulloyd如果你按照我提出的方式編寫了你的​​行爲,而你剛剛被重定向,那麼這意味着對象被正確填充,所以確實不需要錯誤消息。 – Tiramonium