我的应用程序是在用C#.Net编码的Asp.Net MVC3中。 我有包含DropDownList的Views。这些DropDownlist是从某个master填充的。 以下是我的控制器代码。
[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);
}
}
我只是在尝试输入重复记录时才收到错误。示例:如果已经有一个名为Mumbai of State Maharashtra的城市,我仍然会尝试输入Mumbai,Maharashtra的记录。然后我无法显示错误消息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的ViewBag属性。它将所有状态传递给下拉列表。
答案 0 :(得分:1)
当编译器到达
时ModelState.AddModelError("", "This City Already Exists");
它被处理了。因为@Html.DropDownList("CountryID", new SelectList(ViewBag.CountryIDies as System.Collections.IEnumerable, "CountryID", "CountryName"), new { id="Country" })
没有任何价值。
为了克服这一点,我添加了
ViewBag.CountryID = new SelectList(db.CountryMasters, "CountryID", "CountryName");
问题已经解决了。