2009-11-30 75 views
0

我有一個簡單的在用戶輸入RSS源的地址的文本字段。如果該字段爲空我不會採取行動,這是我的標記:ASP.NET MVC簡單驗證我的表單失敗

<%=Html.ValidationSummary() %> 
    <table> 
     <tr> 
      <td> 
       Feed Url: 
      </td> 
      <td> 
       <%=Html.TextBox("url", null, new {@style="width:300px"}) %> 
      </td> 
     </tr></table> 

我的控制也很簡單:

[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult AddFeed(FormCollection collection) 
    { 
     string url = collection.Get("url"); 
     string roles = collection.Get("Roles"); 
     if (string.IsNullOrEmpty(url)) 
     { 
      ModelState.AddModelError("url", "Please provide a propre feed url"); 
     } 
     if (string.IsNullOrEmpty(roles)) 
     { 
      ModelState.AddModelError("Roles", "Please select a valid role"); 
     } 
     if (ModelState.IsValid) 
     { 
      Session["url"] = url; 
      Session["Roles"] = roles; 
      return RedirectToAction("ValidateFeed"); 
     } 
     else 
     { 
      return View(); 
     } 
    } 

當它失敗,將重新加載視圖,這使該行其中一個例外它呈現我的文本框,說有一個空指針異常。這確實botheres我來說,這應該是這麼簡單......但還是即時通訊掙扎

/H4mm3r

編輯請下來的我一直忽視的角色元素的下降,但是從標記刪除它爲簡單起見

回答

0

我認爲你不能使用ModelSate一樣,如果你不這樣做:

UpdateModel(collection); 

TryUpdateModel(collection); 

或參數綁定

public ActionResult AddFeed(YourModelType collection) 

因爲ModelState中不與任何模型相關聯。

作爲參考MSDN說:

的ModelState類

封裝模型 的狀態結合於 動作方法參數的屬性,或到 參數本身。

0

當使用HTML幫助程序時,您可能不能使用null。在您的形式代替試試這個:

<%= Html.TextBox("url", String.Empty, new {@style="width:300px"}) %> 

我沒有測試過,但是這是我想嘗試的第一件事情,因爲錯誤消息。

+0

試過了:-)沒有運氣:-(認爲「奧馬爾」在他的回答中有一個問題,現在就試試吧 – H4mm3rHead 2009-11-30 20:39:48