简体   繁体   中英

Asp.net MVC-fileupload value shows null values in httppost method

On the View:

 <div id="project-contact-form"> @using (Ajax.BeginForm("Apply","Careers", new AjaxOptions { OnSuccess = "onApplySuccess" }, new { @id = "form1", @enctype = "multipart/form-data" })) { <div class="row"> <div class="col-md-12"> <div id="success-project-contact-form" class="no-margin-lr"></div> </div> <div class="col-md-6"> <input type="text" required name="Firstname" id="Firstname" placeholder="First name" class="big-input"> </div> <div class="col-md-6"> <input type="text" required name="Lastname" id="Lastname" placeholder="Last name" class="big-input"> </div> <div class="col-md-6"> <input type="email" required name="Email" id="email" placeholder="E-mail" class="big-input"> </div> <div class="col-md-6"> <input type="text" required name="Mobile" id="mobile" placeholder="Mobile" class="big-input"> </div> <div class="col-md-6"> <input type="file" name="FileUploader" id="files" class="hidden" /> <label for="files" class="float-left cursor-pointer">Upload CV</label> </div> <div class="col-md-12 text-center"> <button id="project-contact-us-button" type="submit" class="btn btn-medium btn-transparent-bnsights btn-rounded md-margin-15px-bottom sm-display-table sm-margin-lr-auto">Send</button> </div> </div> } </div> 

In the Controller: HttpPostedFileBase FileUploader value= null i tried several ways but don't know the reason why it is null

 public ActionResult Apply(ContactUsModel model, HttpPostedFileBase FileUploader)
    {
        SendEmail sendemail = new SendEmail();

        string toEmail = ConfigurationManager.AppSettings["ContactUsEmail"];

        var keys = new Dictionary<string, string>() {
            { "Firstname", model.Firstname },
            { "Lastname", model.Lastname },
            { "Email", model.Email },
            { "Orgnization", model.Orgnization },
            { "Message", model.Message }
        };

        // string body = $"Firstname : {model.Firstname} \n Lastname : {model.Lastname}\n Email : {model.Email} \n Orgnization : {model.Orgnization} \n Message : {model.Message}";
        if (keys != null && keys.Count != 0)
        {
            string body = string.Join(Environment.NewLine, keys.Select(x => $"{x.Key}: {x.Value}"));

            sendemail.Send(new EmailModel()
            {
                Body = body,
                Subject = "Contact Us Message",
                To = new List<string>() { toEmail },


            }, FileUploader);

            return Json(new { val = true }, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(new { val = false }, JsonRequestBehavior.AllowGet);
        }          
    }

Any advice ?

Normally you cannot upload file using Ajax.BeginForm() like Html.BeginForm() . You have to use JavaScript/jQuery to submit the form element.

Here is the solution:

$(document).ready(function(){
    $(document).on("submit", "#form1", function (event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            var formData = new FormData(this);
            var url = this[0].action;

            $.ajax({
              url: url,
              type: 'POST',
              data: formData,
              success: function (response) {
                if (response) {
                  //do necessary work with response
                }
              },
              error: function() {
                //handle error here
              },
              cache: false,
              contentType: false,
              processData: false
            });
            return false;
          });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM