1

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.

1 Answer 1

1

As the compiler was reaching the

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

it was disposed.Hence my @Html.DropDownList("CountryID", new SelectList(ViewBag.CountryIDies as System.Collections.IEnumerable, "CountryID", "CountryName"), new { id="Country" }) was not having any value in it. To overcome this i added

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

And the issue was sorted.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.