我在ienumerable< selectlist>中发现错误 [英] I am geting error in ienumerable<selectlist>

查看:123
本文介绍了我在ienumerable< selectlist>中发现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的错误: -

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已将我的城市从字符串转换为



i have converted my city from string to

IEnumerable

但仍无法正常工作



这里是我的allofcity模型(从这里开始我的城市): -

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; }
   }



这是我的Registerviewmodel: -




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; }

到此: -

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>





我尝试过:



i在没有电子邮件地址验证的情况下在另一个解决方案中拥有相同的东西,它将所选城市从数据库保存到我的registerviewmodel



但在这个解决方案中,我正在使用电子邮件验证并收到此错误



i已经尝试了所有但仍然出现错误



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

推荐答案

)]
public decimal Mobile {get; set;}
[Required]
public string Address {get; set;}
[Required]

public IEnumerable< string> City {get; set;}
")] 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: -

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>





我尝试过:



i在没有电子邮件地址验证的情况下在另一个解决方案中拥有相同的东西,它将所选城市从数据库保存到我的registerviewmodel



但在这个解决方案中,我使用的是电子邮件验证并收到此错误



i已尝试过所有内容但仍出现错误



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


确保 ViewBag 键名在控制器中是统一的, cshtml

如果您只选择一个城市,那么City的数据类型可以从 string [] 更改为 string



参考此示例



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" })


这篇关于我在ienumerable&lt; selectlist&gt;中发现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆