Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
here is my error:-
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The ViewData item that has the key 'City' is of type 'System.String[]' but must be of type 'IEnumerable<SelectListItem>'.


i have converted my city from string to
IEnumerable
But still not working

here is my allofcity model(from here i am getting my city):-
public class allcity
   {
       [Key]
       public int cid { get; set; }
       [Required]
       public string cities { get; set; }
   }

here is my Registerviewmodel:-

public string FirstName { get; set; }
[Required]
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Gender { get; set; }
[Required]
[DataType(DataType.Date)]
public string DOB { get; set; }
[Required]
[RegularExpression("^[0-9]{12}$")]
public decimal Mobile { get; set; }
[Required]
public string Address { get; set; }
[Required]

public IEnumerable<string> City { get; set; }


if i convert this :-
public IEnumerable<string> City { get; set; }
to this:-
public IEnumerable<selectlist> City { get; set; }


then it will not going to save in database

here is my Account Controller

  private ApplicationDbContext db = new ApplicationDbContext();
        // GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            IEnumerable<SelectListItem> item = db.allofcity.Select(C => new SelectListItem
            {
                Value = C.cities,
                Text = C.cities

            });
            ViewBag.citi = item;
            return View();
        }

        //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register([Bind(Exclude = "UserPhoto")]RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // To convert the user uploaded Photo as Byte Array before save to DB
                byte[] imageData = null;
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase poImgFile = Request.Files["UserPhoto"];

                    using (var binary = new BinaryReader(poImgFile.InputStream))
                    {
                        imageData = binary.ReadBytes(poImgFile.ContentLength);
                    }
                }


                var user = new ApplicationUser() { UserName = model.Email , ConfirmPassword=model.ConfirmPassword,
 FirstName = model.FirstName,
 MiddleName = model.MiddleName,
 LastName = model.LastName,
 Gender = model.Gender,
 DOB = model.DOB,
Mobile = model.Mobile,
 Address = model.Address,
City=model.City};
                //Here we pass the byte array to user context to store in db
                user.UserPhoto = imageData;
               
                user.Email = model.Email;
                user.ConfirmedEmail = false;
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage(
                         new System.Net.Mail.MailAddress("myid", "Web Registration"),
                         new System.Net.Mail.MailAddress(user.Email));
                    m.Subject = "Email confirmation";
                    m.Body = string.Format("Dear {0}<BR/>Thank you for your registration, please click on the below link to complete your registration: <a href=\"{1}\" title=\"User Email Confirm\">{1}</a>", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.Email }, Request.Url.Scheme));
                    m.IsBodyHtml = true;
                    System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp-mail.outlook.com");
                    smtp.Credentials = new System.Net.NetworkCredential("my id", "mypassword");
                    smtp.Port = 587;
                    smtp.EnableSsl = true;
                    smtp.Send(m);
                    return RedirectToAction("Confirm", "Account", new { Email = user.Email });
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }


and here is my view:-

<div class="form-group">
        @Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownListFor(Model=>Model.City, (IEnumerable<SelectListItem>)ViewBag.citi, "Select City", new { @class = "form-control" })
        </div>
    </div>


What I have tried:

i Have same thing in another solution without Email Address verification , and it saves the selected city from the data base to my registerviewmodel

but in this solution i am using email verification and getting this error

i have tried everything but still error comes
Posted
Updated 4-Apr-17 22:08pm
v2

1 solution

Make sure the ViewBag key name is uniform across controller and the cshtml
if you are selecting only one city then the data type of the City can be changed from string[] to string

refer this example

public class MyModel
   {
       public string City { get; set; }
       public string OtherProp {get; set;}
   }

   public class HomeController : Controller
   {
       public ActionResult Index()
       {
           List<SelectListItem> lst = new List<SelectListItem>();
           lst.Add(new SelectListItem() { Text = "One", Value= "1" });
           lst.Add(new SelectListItem() { Text = "two", Value = "2" });
           lst.Add(new SelectListItem() { Text = "three", Value = "3" });
           IEnumerable<SelectListItem> item = lst.AsEnumerable();
           ViewBag.ViewBagCity = item;
           MyModel obj = new MyModel();
           return View();
       }

   }



@model MyModel
   @Html.DropDownListFor(Model => Model.City, (IEnumerable<SelectListItem>)ViewBag.ViewBagCity, "Select City", new { @class = "form-control" })
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900