4

I am new to MVC and need help to upload File , I am using umbraco. 7.2.1 I am trying to send mail with mail with attachment Following is my code for the same. Partial View ==>name Contact

 using (Html.BeginUmbracoForm<ContactVController>("HandleContactSubmit"))   
    {
       @Html.LabelFor(model => model.Name)<br />
       @Html.EditorFor(model => model.Name)<br />
       @Html.ValidationMessageFor(model => model.Name)<br />

       @Html.LabelFor(model => model.Email)<br />
       @Html.EditorFor(model => model.Email)<br />
       @Html.ValidationMessageFor(model => model.Email)<br />
          <input type="file" name="file" id="file" />
        <p>
           <input type="submit" value="Submit" />
       </p>
    }

Model

public class ContactVModel  
{
    [Required]
    public string Name { get; set; }
    [Required]
    [RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")]
    public string Email { get; set; }
    [Required]
    public string Message { get; set; }
    public HttpPostedFileBase attachment { get; set; }
}

Controller

public class ContactVController : SurfaceController
    {
    [HttpPost]
    public ActionResult HandleContactSubmit(ContactVModel model)
        {
,.......... ...... ....

  ,.......... ...... ....  

    MailBody + = model.Name ;
MailBody + = model.Email;

SendMail( MailBody )
}

But I do not know access model.attachment , How can I do so to send mail with attachment (the file which is uploaded ) (As I am able to acces Name, Email, etc.) I have referred following post but I could not able to access attachment

MVC 4 Razor File Upload

but I could not make it out

Community
  • 1
  • 1
BJ Patel
  • 6,148
  • 11
  • 47
  • 81

1 Answers1

4

Change the input from

<input type="file" name="file" id="file" />

to

<input type="file" name="attachment" id="attachment" /> 

So the property in the model matches the input field.

I'm currently using the following:

In the cshtml file:
@Html.UploadFor(model=> model.Attachment)

static public class HtmlExtensions
{
    public static IHtmlString UploadFor<TSource, TResult>(this HtmlHelper<TSource> html, Expression<Func<TSource, TResult>> propertyExpression)
    {
        var memberName = Reflection.GetPropertyName(propertyExpression);
        return new HtmlString($"<input type=\"file\" name=\"{memberName}\" id=\"{memberName}\">");
    }
}

class Reflection
{
    public static string GetPropertyName<TSource, TResult>(Expression<Func<TSource, TResult>> propertyExpression)
    {
        return (propertyExpression.Body as MemberExpression).Member.Name;
    }
}
CodingBarfield
  • 3,392
  • 2
  • 27
  • 54