与 Postal MVC 的附件不起作用

发布于 2024-12-05 09:21:32 字数 7703 浏览 1 评论 0原文

我有一个 MVC3 项目。在我的联系页面中,我想添加向客户发送的电子邮件添加附件的可能性。

我使用的是邮政。它工作得很好,但我无法让附件工作。

这是我处理此问题的代码部分:

我有一个模型类:

public class ContactEmail
{
    [ScaffoldColumn(false)]
    public int id { get; set; }

    [Required(ErrorMessage = "Name is required!")]
    [DataType(DataType.Text)]
    [DisplayName("Name")]
    public string name { get; set; }

    [Required(ErrorMessage = "Email Address is required!")]
    [DataType(DataType.EmailAddress)]
    [DisplayName("Email Address")]
    [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email Address is not valid.")]
    public string email { get; set; }

    [Required(ErrorMessage = "Country is required!")]
    [DisplayName("Country")]
    public string country { get; set; }

    [DisplayName("Subject")]
    public string subject { get; set; }

    [Required(ErrorMessage = "Message is required!")]
    [DisplayName("Message")]
    [StringLength(1500)]
    public string message { get; set; }

    [ScaffoldColumn(false)]
    public DateTime datetime { get; set; }

    public HttpPostedFileBase attachment { get; set; }

这是我的邮政控制器:

public class PostalController : Controller
{
    [HttpPost]
    public ActionResult Send(ContactEmail model)
    {

        if (ModelState.IsValid)
        {
            Random random = new Random();
            var ticket = random.Next(1000000000, 2000000000);

            dynamic courriel = new Email("Postal");
            courriel.To = "[email protected]";
            courriel.Name = model.name;
            courriel.Country = model.country;
            courriel.Subject = model.subject;
            courriel.From = model.email;
            courriel.Message = model.message;
            courriel.TicketId = ticket;
            courriel.Attachment = model.attachment;
            //if (model.Attachment != null && model.Attachment.ContentLength > 0)
            //{
            //    var attachment = new Attachment(model.Attachment.InputStream, model.Attachment.FileName);
            //    courriel.Attachments.Add(attachment);
            //}
            //courriel.Attachment = model.Attachment; 

            courriel.Attach(new Attachment(model.attachment.InputStream, model.attachment.FileName));

            Task task = courriel.SendAsync();

            //courriel.Send();

            return RedirectToAction("Sent", "Contact");
        }

        ViewData["MessageSent"] = false;

        return View("~/Views/Contact/Contact.cshtml");
    }

最后这是我在 中使用的表单Contact.cshtml 视图

@using (Html.BeginForm("Send", "Postal"))
{        
    @Html.ValidationSummary(false)

    <p>
       @Html.LabelFor(model => model.name)
       @Html.TextBoxFor(model => model.name, new { @size = 35 })
       @Html.ValidationMessageFor(model => model.name, "*")
    </p>                      
    <p>
       @Html.LabelFor(model => model.email)
       @Html.TextBoxFor(model => model.email, new { @size = 35 })
       @Html.ValidationMessageFor(model => model.email, "*")
    </p>
    <p>
       @Html.LabelFor(model => model.subject)
       @Html.DropDownList(
           "subject", 
           new[] { 
               new SelectListItem { 
                   Text = "NT Indicator Quote", 
                   Value = "NT Indicator Quote" 
               }, 
               new SelectListItem { 
                   Text = "NT Strategy Quote", 
                   Value = "NT Strategy Quote" 
               }, 
               new SelectListItem { 
                   Text = "Comments", 
                   Value = "Comments" 
               }, 
               new SelectListItem { 
                   Text = "other", 
                   Value = "other" 
               }
           }
       ); // @Html.DropDownList(
       @Html.ValidationMessageFor(model => model.subject, "*")
    </p>
    <p>
       @Html.LabelFor(model => model.message)
       @Html.TextAreaFor(model => model.message, new { @cols = 50, @rows = 10 })
       @Html.ValidationMessageFor(model => model.message, "*")
    </p>
    <p>
       @Html.LabelFor(model => model.attachment)
       @Html.TextBoxFor(model => model.attachment, new { type = "file" })
       @Html.ValidationMessageFor(model => model.attachment)
    </p>          
    <p><input type="submit" id="submit" name="submit" value="Submit" /></p>            
} <!-- End form -->

我收到以下错误消息:

未将对象引用设置为对象的实例。 描述:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。
异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。
来源错误: 第 44 行:courriel.Attach(new Attachment(model.attachment.InputStream, model.attachment.FileName));

你能帮我找出这里的问题吗? 谢谢 !

以下是查看源代码的 HTML:

<form action="/Postal/Send?enctype=multipart%2Fform-data" method="post">
    <div class="validation-summary-valid" data-valmsg-summary="true">
        <ul>
            <li style="display:none"></li>
        </ul>
    </div>
    <p>
        <label for="name">Name</label>
        <input data-val="true" data-val-required="Name is required!" id="name" name="name" size="35" type="text" value="" />
        <span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="false">*</span>
    </p>
    <p>
        <label for="email">Email Address</label>
        <input data-val="true" data-val-regex="Email Address is not valid." data-val-regex-pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}" data-val-required="Email Address is required!" id="email" name="email" size="35" type="text" value="" />
        <span class="field-validation-valid" data-valmsg-for="email" data-valmsg-replace="false">*</span>
    </p>
    <p>
        <label for="subject">Subject</label>
        <select id="subject" name="subject">
            <option value="NT Indicator Quote">NT Indicator Quote</option>
            <option value="NT Strategy Quote">NT Strategy Quote</option>
            <option value="Comments">Comments</option>
            <option value="other">other</option>
        </select>
        <span class="field-validation-valid" data-valmsg-for="subject" data-valmsg-replace="false">*</span>
    </p>
    <p>
        <label for="message">Message</label>
        <textarea cols="50" data-val="true" data-val-length="The field Message must be a string with a maximum length of 1500." data-val-length-max="1500" data-val-required="Message is required!" id="message" name="message" rows="10">
        </textarea>
        <span class="field-validation-valid" data-valmsg-for="message" data-valmsg-replace="false">*</span>
    </p>
    <p>
        <label for="attachment">attachment</label>
        <input id="attachment" name="attachment" type="file" value="" />
        <span class="field-validation-valid" data-valmsg-for="attachment" data-valmsg-replace="true"></span>
    </p>
    <p>
        <input type="submit" id="submit" name="submit" value="Submit" />
    </p>
</form> <!-- End form -->

    </div>

I have a MVC3 project. In my contact page I would like to add the possibility of adding an attachment to Email sent by customer.

I am using Postal. It works well but I can't get the attachment working.

Here is the part of my code dealing with this:

I have a model class:

public class ContactEmail
{
    [ScaffoldColumn(false)]
    public int id { get; set; }

    [Required(ErrorMessage = "Name is required!")]
    [DataType(DataType.Text)]
    [DisplayName("Name")]
    public string name { get; set; }

    [Required(ErrorMessage = "Email Address is required!")]
    [DataType(DataType.EmailAddress)]
    [DisplayName("Email Address")]
    [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email Address is not valid.")]
    public string email { get; set; }

    [Required(ErrorMessage = "Country is required!")]
    [DisplayName("Country")]
    public string country { get; set; }

    [DisplayName("Subject")]
    public string subject { get; set; }

    [Required(ErrorMessage = "Message is required!")]
    [DisplayName("Message")]
    [StringLength(1500)]
    public string message { get; set; }

    [ScaffoldColumn(false)]
    public DateTime datetime { get; set; }

    public HttpPostedFileBase attachment { get; set; }

Here is my Postal Controller:

public class PostalController : Controller
{
    [HttpPost]
    public ActionResult Send(ContactEmail model)
    {

        if (ModelState.IsValid)
        {
            Random random = new Random();
            var ticket = random.Next(1000000000, 2000000000);

            dynamic courriel = new Email("Postal");
            courriel.To = "[email protected]";
            courriel.Name = model.name;
            courriel.Country = model.country;
            courriel.Subject = model.subject;
            courriel.From = model.email;
            courriel.Message = model.message;
            courriel.TicketId = ticket;
            courriel.Attachment = model.attachment;
            //if (model.Attachment != null && model.Attachment.ContentLength > 0)
            //{
            //    var attachment = new Attachment(model.Attachment.InputStream, model.Attachment.FileName);
            //    courriel.Attachments.Add(attachment);
            //}
            //courriel.Attachment = model.Attachment; 

            courriel.Attach(new Attachment(model.attachment.InputStream, model.attachment.FileName));

            Task task = courriel.SendAsync();

            //courriel.Send();

            return RedirectToAction("Sent", "Contact");
        }

        ViewData["MessageSent"] = false;

        return View("~/Views/Contact/Contact.cshtml");
    }

and finally here is the form I use in my Contact.cshtml view:

@using (Html.BeginForm("Send", "Postal"))
{        
    @Html.ValidationSummary(false)

    <p>
       @Html.LabelFor(model => model.name)
       @Html.TextBoxFor(model => model.name, new { @size = 35 })
       @Html.ValidationMessageFor(model => model.name, "*")
    </p>                      
    <p>
       @Html.LabelFor(model => model.email)
       @Html.TextBoxFor(model => model.email, new { @size = 35 })
       @Html.ValidationMessageFor(model => model.email, "*")
    </p>
    <p>
       @Html.LabelFor(model => model.subject)
       @Html.DropDownList(
           "subject", 
           new[] { 
               new SelectListItem { 
                   Text = "NT Indicator Quote", 
                   Value = "NT Indicator Quote" 
               }, 
               new SelectListItem { 
                   Text = "NT Strategy Quote", 
                   Value = "NT Strategy Quote" 
               }, 
               new SelectListItem { 
                   Text = "Comments", 
                   Value = "Comments" 
               }, 
               new SelectListItem { 
                   Text = "other", 
                   Value = "other" 
               }
           }
       ); // @Html.DropDownList(
       @Html.ValidationMessageFor(model => model.subject, "*")
    </p>
    <p>
       @Html.LabelFor(model => model.message)
       @Html.TextAreaFor(model => model.message, new { @cols = 50, @rows = 10 })
       @Html.ValidationMessageFor(model => model.message, "*")
    </p>
    <p>
       @Html.LabelFor(model => model.attachment)
       @Html.TextBoxFor(model => model.attachment, new { type = "file" })
       @Html.ValidationMessageFor(model => model.attachment)
    </p>          
    <p><input type="submit" id="submit" name="submit" value="Submit" /></p>            
} <!-- End form -->

I get the following error message :

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 44: courriel.Attach(new Attachment(model.attachment.InputStream, model.attachment.FileName));

Could you please help me find out the problem here ?
Thank you !

Here is the HTML from the view source :

<form action="/Postal/Send?enctype=multipart%2Fform-data" method="post">
    <div class="validation-summary-valid" data-valmsg-summary="true">
        <ul>
            <li style="display:none"></li>
        </ul>
    </div>
    <p>
        <label for="name">Name</label>
        <input data-val="true" data-val-required="Name is required!" id="name" name="name" size="35" type="text" value="" />
        <span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="false">*</span>
    </p>
    <p>
        <label for="email">Email Address</label>
        <input data-val="true" data-val-regex="Email Address is not valid." data-val-regex-pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}" data-val-required="Email Address is required!" id="email" name="email" size="35" type="text" value="" />
        <span class="field-validation-valid" data-valmsg-for="email" data-valmsg-replace="false">*</span>
    </p>
    <p>
        <label for="subject">Subject</label>
        <select id="subject" name="subject">
            <option value="NT Indicator Quote">NT Indicator Quote</option>
            <option value="NT Strategy Quote">NT Strategy Quote</option>
            <option value="Comments">Comments</option>
            <option value="other">other</option>
        </select>
        <span class="field-validation-valid" data-valmsg-for="subject" data-valmsg-replace="false">*</span>
    </p>
    <p>
        <label for="message">Message</label>
        <textarea cols="50" data-val="true" data-val-length="The field Message must be a string with a maximum length of 1500." data-val-length-max="1500" data-val-required="Message is required!" id="message" name="message" rows="10">
        </textarea>
        <span class="field-validation-valid" data-valmsg-for="message" data-valmsg-replace="false">*</span>
    </p>
    <p>
        <label for="attachment">attachment</label>
        <input id="attachment" name="attachment" type="file" value="" />
        <span class="field-validation-valid" data-valmsg-for="attachment" data-valmsg-replace="true"></span>
    </p>
    <p>
        <input type="submit" id="submit" name="submit" value="Submit" />
    </p>
</form> <!-- End form -->

    </div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥醉 2024-12-12 09:21:32

如果要上传文件,您需要将 enctype="multipart/form-data" 属性附加到表单:

@using (Html.BeginForm("Send", "Postal", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{
    ...
}

另请查看此 博客文章,作者:Haacked。

You need to append the enctype="multipart/form-data" attribute to the form if you want to upload files:

@using (Html.BeginForm("Send", "Postal", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{
    ...
}

Also checkout this blog post by the Haacked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文