My application is in Asp.Net MVC3 coded in C#.Net. I have Views which contains DropDownList.These DropDownlist are populated from Certain master. Below is my Controller Code.
[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);
}
}
Im getting the error only when im trying to enter Duplicate record.Example: If there is already a City named Mumbai of State Maharashtra,and i still try to enter a record with Mumbai,Maharashtra.Then im not able to show the error message ModelState.AddModelError("", "This City Already Exists");.Rather im getting the System.ArgumentNullException: Value cannot be null. error.
Below is my View code.
@Html.DropDownList("CountryID", new SelectList(ViewBag.CountryIDies as System.Collections.IEnumerable, "CountryID", "CountryName"), new { id="Country" })
This is my DropDownlist and im getting error on the same line. This code works fine when im using it in those views which doesnt contain DropDownList. I have debugged and checked the values in Testmaster,its giving correct value of the selected combo. Also i have checked the ViewBag property that is passing the Value to DropDownList.Its passing all the states to the dropdownlist.