2012-01-03 18 views
1

我的應用程序是用C#.Net編碼的Asp.Net MVC3。 我有意見,其中包含DropDownList.These DropDownlist從某些主人填充。 以下是我的控制器代碼。參數無異常由MVC3中的用戶代碼處理

[HttpPost] 
      public ActionResult TestCreate(MainMaster Testmaster) 
      { 
      var recExists= from c in db.MainMaster 
         where c.CityName == Testmaster.CityName &&             c.StateID==Testmaster.StateID 
         select c; 

      if (nid.Count()>0) 
       { 
        ModelState.AddModelError("", "This City Already Exists"); 
       } 
      if (ModelState.IsValid) 
      { 
        db.MainMaster.Add(Testmaster); 
        db.SaveChanges(); 
        return RedirectToAction("Index"); 
      } 
      else 
      { 
       return View(Testmaster); 
      } 
      } 

只有當我試圖輸入重複記錄時纔會出現錯誤。 例如:如果已經有一個城市名爲孟買馬哈拉施特拉邦,我仍然試圖與孟買,馬哈拉施特拉邦進行記錄。然後我不能顯示錯誤信息ModelState.AddModelError("", "This City Already Exists");。相反,我得到System.ArgumentNullException: Value cannot be null.錯誤。

以下是我的查看代碼。

@Html.DropDownList("CountryID", new SelectList(ViewBag.CountryIDies as System.Collections.IEnumerable, "CountryID", "CountryName"), new { id="Country" }) 

這是我的DropDownlist和即時獲取錯誤在同一行。 此代碼工作正常時,即時通訊在那些不包含DropDownList的視圖中使用它。 我已經調試並檢查了Testmaster中的值,它給出了所選組合的正確值。 另外我已經檢查了將DropDownList.Its傳遞給下拉列表的所有狀態的ViewBag屬性。

回答

1

由於編譯器到達

ModelState.AddModelError("", "This City Already Exists"); 

它disposed.Hence我@Html.DropDownList("CountryID", new SelectList(ViewBag.CountryIDies as System.Collections.IEnumerable, "CountryID", "CountryName"), new { id="Country" })不具有任何價值。 爲了克服這個問題,我增加

ViewBag.CountryID = new SelectList(db.CountryMasters, "CountryID", "CountryName"); 

而且問題進行了排序。

相關問題