Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 有一个错误:ViewData键为“0”;“地址”;属于“类型”;System.String“;,但它必须是一种类型;IEnumerable<;选择列表项>&引用;_C#_Asp.net Mvc_Asp.net Mvc 4_Html.dropdownlistfor_Viewbag - Fatal编程技术网

C# 有一个错误:ViewData键为“0”;“地址”;属于“类型”;System.String“;,但它必须是一种类型;IEnumerable<;选择列表项>&引用;

C# 有一个错误:ViewData键为“0”;“地址”;属于“类型”;System.String“;,但它必须是一种类型;IEnumerable<;选择列表项>&引用;,c#,asp.net-mvc,asp.net-mvc-4,html.dropdownlistfor,viewbag,C#,Asp.net Mvc,Asp.net Mvc 4,Html.dropdownlistfor,Viewbag,我用这张表格寄邮件。当我按下“发送”按钮时,我看到错误“带有键“address”的ViewData的类型为“System.String”,但它必须是“IEnumerable”类型 有趣的是,这封信已经寄出了,但申请书却在秋天。。。 帮帮我,伙计们 这是我的模型: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcLibraly.Models {

我用这张表格寄邮件。当我按下“发送”按钮时,我看到错误“带有键“address”的ViewData的类型为“System.String”,但它必须是“IEnumerable”类型

有趣的是,这封信已经寄出了,但申请书却在秋天。。。 帮帮我,伙计们

这是我的模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcLibraly.Models
{
    public class MailModel
    {
        public string To { get; set; }
        public string Adress { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }

    }
}
这是控制器:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using MvcLibraly.Models;
using System.Web.Mvc.Html;
using System.Web.UI.WebControls;


namespace MvcLibraly.Controllers
{
    public class SendMailerController : Controller
    {
        private BookDBContext db = new BookDBContext();
        //
        // GET: /SendMailer/

        public ActionResult Index(string nameEmail)
        {



            var EmailLst = new List<string>();

            var EmailQry = from f in db.Uchets
                           orderby f.Adress where f.DateVoz < DateTime.Now
                           select f.Adress;
            EmailLst.AddRange(EmailQry.Distinct());
            ViewBag.nameEmail = new SelectList(EmailLst);



            return View();
        }

        /// <summary>
        /// Send Mail with Gmail
        /// </summary>
        /// <param name="objModelMail">MailModel Object, keeps all properties</param>
        /// <param name="fileUploader">Selected file data, example-filename,content,content type(file type- .txt,.png etc.),length etc.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(MvcLibraly.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
        {





            if (ModelState.IsValid)
            {


                string from = "myadress@gmail.com"; //example:- sourabh9303@gmail.com
                using (MailMessage mail = new MailMessage(from, objModelMail.Adress))
                {
                    mail.Subject = objModelMail.Subject;
                    mail.Body = objModelMail.Body;
                    if (fileUploader != null)
                    {
                        string fileName = Path.GetFileName(fileUploader.FileName);
                        mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
                    }
                    mail.IsBodyHtml = false;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    NetworkCredential networkCredential = new NetworkCredential(from, "mypassword");
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = networkCredential;
                    smtp.Port = 587;
                    smtp.Send(mail);
                    ViewBag.Message = "Sent";
                    return View("Index", objModelMail);
                }
            }
            else
            {
                return View();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using MvcLibraly.Models;
using System.Web.Mvc.Html;
using System.Web.UI.WebControls;


namespace MvcLibraly.Controllers
{
    public class SendMailerController : Controller
    {
        private BookDBContext db = new BookDBContext();
        //
        // GET: /SendMailer/

        private List<SelectListItem> GetEmailList()
{
    var emailLst = (from f in db.Uchets
                    orderby f.Adress
                    where f.DateVoz < DateTime.Now
                    select new SelectListItem
                    {
                        Text = f.Adress,
                        Value = f.Adress
                    }).Distinct().ToList();

    return emailLst;
}

public ActionResult Index(string nameEmail)
{
    ViewBag.nameEmail = GetEmailList();
    return View();
}

[HttpPost]
public ActionResult Index(MvcLibraly.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
{
    if (ModelState.IsValid)
    {
        // ...
    }
    else
    {
        ViewBag.nameEmail = GetEmailList();
        return View();
    }
}
更新

控制器:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using MvcLibraly.Models;
using System.Web.Mvc.Html;
using System.Web.UI.WebControls;


namespace MvcLibraly.Controllers
{
    public class SendMailerController : Controller
    {
        private BookDBContext db = new BookDBContext();
        //
        // GET: /SendMailer/

        public ActionResult Index(string nameEmail)
        {



            var EmailLst = new List<string>();

            var EmailQry = from f in db.Uchets
                           orderby f.Adress where f.DateVoz < DateTime.Now
                           select f.Adress;
            EmailLst.AddRange(EmailQry.Distinct());
            ViewBag.nameEmail = new SelectList(EmailLst);



            return View();
        }

        /// <summary>
        /// Send Mail with Gmail
        /// </summary>
        /// <param name="objModelMail">MailModel Object, keeps all properties</param>
        /// <param name="fileUploader">Selected file data, example-filename,content,content type(file type- .txt,.png etc.),length etc.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(MvcLibraly.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
        {





            if (ModelState.IsValid)
            {


                string from = "myadress@gmail.com"; //example:- sourabh9303@gmail.com
                using (MailMessage mail = new MailMessage(from, objModelMail.Adress))
                {
                    mail.Subject = objModelMail.Subject;
                    mail.Body = objModelMail.Body;
                    if (fileUploader != null)
                    {
                        string fileName = Path.GetFileName(fileUploader.FileName);
                        mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
                    }
                    mail.IsBodyHtml = false;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    NetworkCredential networkCredential = new NetworkCredential(from, "mypassword");
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = networkCredential;
                    smtp.Port = 587;
                    smtp.Send(mail);
                    ViewBag.Message = "Sent";
                    return View("Index", objModelMail);
                }
            }
            else
            {
                return View();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using MvcLibraly.Models;
using System.Web.Mvc.Html;
using System.Web.UI.WebControls;


namespace MvcLibraly.Controllers
{
    public class SendMailerController : Controller
    {
        private BookDBContext db = new BookDBContext();
        //
        // GET: /SendMailer/

        private List<SelectListItem> GetEmailList()
{
    var emailLst = (from f in db.Uchets
                    orderby f.Adress
                    where f.DateVoz < DateTime.Now
                    select new SelectListItem
                    {
                        Text = f.Adress,
                        Value = f.Adress
                    }).Distinct().ToList();

    return emailLst;
}

public ActionResult Index(string nameEmail)
{
    ViewBag.nameEmail = GetEmailList();
    return View();
}

[HttpPost]
public ActionResult Index(MvcLibraly.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
{
    if (ModelState.IsValid)
    {
        // ...
    }
    else
    {
        ViewBag.nameEmail = GetEmailList();
        return View();
    }
}
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
Net系统;
使用System.Net.Mail;
使用System.Web;
使用System.Web.Mvc;
使用系统数据;
使用System.Data.Entity;
使用MvcLibraly.Models;
使用System.Web.Mvc.Html;
使用System.Web.UI.WebControl;
命名空间MvcLibraly.Controllers
{
公共类SendMailerController:控制器
{
private BookDBContext db=新建BookDBContext();
//
//获取:/SendMailer/
私有列表GetEmailList()
{
var emailLst=(来自db.Uchets中的f
orderby f.Address
其中f.DateVoz
视图:

@model MvcLibraly.Models.MailModel

@{
    ViewBag.Title = "Send Mail";
}
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script>
    $(document).ready(function () {
        if ('@ViewBag.Message' == 'Sent') {
            alert('Good!');
        }
    });
</script>
<h2>Send mail</h2>
<fieldset>
    <legend>Send Email
    </legend> 
   @using (@Html.BeginForm("Index", "SendMailer", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))
    {
     @Html.ValidationSummary()
        <table>
            <tr>

                <td>To:
                </td>
                <td>
                    @*@Html.TextBoxFor(m => m.To)*@
                    @Html.DropDownListFor(model => model.Adress, (IList<SelectListItem>) ViewBag.nameEmail, new { style = "width: 310px" })
                    @Html.ValidationMessageFor(model => model.Adress, "Error!")
                </td>
            </tr>
            <tr>
                <td>Subject:
                </td>
                <td>
                    @Html.TextBoxFor(model => model.Subject)
                     @Html.ValidationMessageFor(model => model.Subject, "Error!")
                </td>
            </tr>
            @*<tr>
                <td>Attachment
                </td>
                <td>
                    <input type="file" name="fileUploader" />
                </td>
            </tr>*@
            <tr>
                <td>Body:
                </td>
                <td>
                    @Html.TextAreaFor(model => model.Body)
                     @Html.ValidationMessageFor(model => model.Body, "Error!")
                </td>
            </tr> 
        </table>    


        <input type="submit" value="Send" />
    }
</fieldset>
@model MvcLibraly.Models.MailModel
@{
ViewBag.Title=“发送邮件”;
}
$(文档).ready(函数(){
如果('@ViewBag.Message'=='Sent'){
警惕(“好!”);
}
});
寄信
发送电子邮件
@使用(@Html.BeginForm(“Index”、“SendMailer”、FormMethod.Post、new{@id=“form1”、@enctype=“multipart/formdata”}))
{
@Html.ValidationSummary()
致:
@*@Html.TextBoxFor(m=>m.To)*@
@Html.DropDownListFor(model=>model.address,(IList)ViewBag.namemail,新的{style=“width:310px”})
@Html.ValidationMessageFor(model=>model.address,“Error!”)
主题:
@Html.TextBoxFor(model=>model.Subject)
@Html.ValidationMessageFor(model=>model.Subject,“Error!”)
@*
附件
*@
正文:
@Html.TextAreaFor(model=>model.Body)
@Html.ValidationMessageFor(model=>model.Body,“Error!”)
}

ViewBag.nameEmail必须是IEnumerable,因此这应该在您的HttpGet操作中修复。此外,在HttpPost操作中,如果模型无效(“else”部分),您还应该再次返回电子邮件列表。否则ViewBag.nameEmail为null或空。这是控制器中的修复:

private List<SelectListItem> GetEmailList()
{
    var emailLst = (from f in db.Uchets
                    orderby f.Adress
                    where f.DateVoz < DateTime.Now
                    select new SelectListItem
                    {
                        Text = f.Adress,
                        Value = f.Adress
                    }).Distinct().ToList();

    return emailLst;
}

public ActionResult Index(string nameEmail)
{
    ViewBag.nameEmail = GetEmailList();
    return View();
}

[HttpPost]
public ActionResult Index(MvcLibraly.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
{
    if (ModelState.IsValid)
    {
        // ...
    }
    else
    {
        ViewBag.nameEmail = GetEmailList();
        return View();
    }
}
private List GetEmailList()
{
var emailLst=(来自db.Uchets中的f
orderby f.Address
其中f.DateVoz
…在您看来,这是一个解决方案:

@Html.DropDownListFor(model => model.Adress, (IList<SelectListItem>) ViewBag.nameEmail, new { style = "width: 310px" })
@Html.DropDownListFor(model=>model.address,(IList)ViewBag.namemail,新的{style=“width:310px”})
希望有帮助;)

在“[HttpPost]”之前的“if(ModelState.IsValid)”必须是“ViewBag.nameMail=GetEmailList();”