We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to upload a file with other form fields using MVC

I am having a hard time finding sample code for how to use the file uploader with MVC. I have a form that opens in a modal and need to collect a couple pieces of info form the user such as name, and then upload the file and write values to a table in the database. If you could please provide an example of this using an ajax call  call I would greatly appreciate it.

Thanks,

11 Replies

PO Prince Oliver Syncfusion Team June 17, 2019 11:26 AM UTC

Hi Adam, 

Thank you for contacting us. 

We can use the Synchronous upload mode in uploader in the form to upload the select file along with the form values. For more information, please refer to the following links 


Let us know if you need any further assistance on this. 

Regards, 
Prince 



UN Unknown July 11, 2019 04:11 PM UTC

Thank you for these links. I had seen these already though. I am using a modal for the form and I need to get the values to my controller and write the form values to the database as well as upload the file. I am trying to use an ajax call to pass the form values to my controller, but I can't find anything that shows me how to get the Upload file value into the controller to save to the drive and write the name of the file to the database. Are there any examples of this?

Thanks,
Adam


PO Prince Oliver Syncfusion Team July 12, 2019 11:58 AM UTC

Hi Adam, 

Thank you for your update. 

As per your requirement, we have prepared a sample to upload files along with form data using AJAX post. Kindly refer to the following code. 

[View] 
<form id="EmailRequestForm"> 
    <div class="form-group" style="padding-top: 11px;"> 
        <div class="e-float-input"> 
            <input type="text" id="Recipient" name="Recipient"> 
            <span class="e-float-line"></span> 
            <label class="e-float-text e-label-top" for="Recipient">Recipient</label> 
        </div> 
    </div> 
    <div class="form-group" style="padding-top: 11px;"> 
        <div class="e-float-input"> 
            <input type="text" id="MessageContent" name="MessageContent"> 
            <span class="e-float-line"></span> 
            <label class="e-float-text e-label-top" for="MessageContent">MessageContent</label> 
        </div> 
    </div> 
    <div class="form-group" style="padding-top: 11px;"> 
        <div class="e-float-input"> 
            @Html.EJS().Uploader("FileUpload").AutoUpload(false).Multiple(false).Render() 
        </div> 
    </div> 
    <input type="button" class="submit-btn e-btn" id="btn" value="Post via AJAX" /> 
</form> 
 
<script type="text/javascript"> 
    $(function () { 
        $("#btn").click(function (e) { 
            var formdata = new FormData($("#EmailRequestForm")[0]); 
            $.ajax({ 
                url: "@Url.Action("ProcessEmailrequest")", 
                data: formdata, 
                success: function (data) { 
                    // Do something here when it is finished 
                }, 
                type: 'POST', 
                cache: false, 
                contentType: false, 
                processData: false 
            }); 
            e.stopPropagation(); 
        }); 
    }); 
</script> 

[Controller] 
[HttpPost] 
public ActionResult ProcessEmailrequest() 
{ 
    var recipient = Request["Recipient"]; 
    var content = Request["MessageContent"]; 
    var file = Request.Files["FileUpload"]; 
    // Save the files and values to the database here 
 
    return View("Index"); 
} 

We have attached  the sample for your reference, please find it in the following location: 

Let us know if you need any further assistance on this. 

Regards, 
Prince 



UN Unknown July 12, 2019 03:51 PM UTC

Hi Prince,

Thanks for the example, it all works good so far except for the file upload. When it gets to the controller I get the first to field values but the "file" is null. I tried running the sample project also to see if I was missing something but get the same result. How do I get the file to be able to save to the drive and write the filename to the database?

Thanks,
Adam


UN Unknown July 13, 2019 01:28 AM UTC

HI Prince,

I worked out getting the filename. I am successfully saving to the drive and writing what I need to the database. What I need help with now is, how do I get it to return and refresh the modal for a new upload. Any help you could provide would be greatly appreciated.

Thanks,
Adam


PO Prince Oliver Syncfusion Team July 16, 2019 01:36 PM UTC

Hello Adam, 
 
Thank you for your update. 
 
We have checked the reported scenario. By default, when the multiple property is set as false, the uploaded model will be refreshed for every uploader request. So there is no need to refresh it again. To save the file in database, convert the files to binary and then store it in the database. Kindly refer to the following UG documentation link 

If still issue persists, kindly provide the below details that help us to check and provide exact solution at our end. 
  1. Code snippet
  2. Exact requirement
  3. If possible reproduce the issue in provided sample
  4. Video demonstration or screenshots of the requirement
 
Regards, 
Prince 



UN Unknown July 26, 2019 02:27 AM UTC

Hi Prince,

I am still having a problem with refreshing the form after uploading. I have the multiple property set to false and it goes to my controller and does the upload and then writes the form info to my database. But then the form is just left with no indication that anything happened. I would like to have the form reset for another upload, or at least return a message stating the success. Here is my code for the upload page, it's a partial that I open in a modal window. The submit button uses the ajax call and goes to a method in the controller, but when the method is finished, nothing else happens. If  you need to see the code in the controller also, or the page that I open the modal in I can provide as well.

Thanks for any help you can provide.

Adam

@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@using Syncfusion.EJ2.DropDowns
@using Tracker4.Helpers

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="max-height: 50%;">
        <div class="modal-content panel panel-default">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <span id="apiCallIndicator" style="float:right; margin-right:20px; display: none; "></span>

                <h4 class="modal-title">Add New Document</h4>
            </div>
            <div class="modal-body">

                    {*@
                @Html.AntiForgeryToken()
                <form id="DocUploadForm">
                    <div class="control_wrapper" id="control_wrapper">
                        <!-- Initialize Uploader -->
                        <input type="hidden" id="Ageid" name="Ageid" value="@ViewBag.AgeId" />
                        <div class="form-group" style="padding-top: 11px;">
                            <div class="e-float-input">
                                <input type="text" value="@ViewBag.Agency" id="Agency" name="Agency" data-required-message="* Enter a agency" required="" data-msg-containerid="agencyError">
                                <span class="e-float-line"></span>
                                <label class="e-float-text e-label-top" for="title">Agency</label>
                            </div>
                            <div id="nameError"></div>
                        </div>
                        <div class="form-group" style="padding-top: 11px;">
                            <div class="e-float-input">
                                <input type="text" id="Title" name="Title" data-required-message="* Enter a title" required="" data-msg-containerid="titleError">
                                <span class="e-float-line"></span>
                                <label class="e-float-text e-label-top" for="title">Title</label>
                            </div>
                            <div id="nameError"></div>
                        </div>
                        <div class="form-group" style="padding-top: 11px;">
                            <div class="e-float-input upload-area">
                            </div>
                            <div id="uploadError"></div>
                            @Html.EJS().Uploader("FileUpload").AutoUpload(false).Multiple(false).Render()
                        </div>

                        <div class="submitBtn">
                            <input type="button" class="submit-btn e-btn" id="btn" value="Upload Doc" />
                        </div>
                        @Html.EJS().Dialog("confirmationDialog").Header("Success").ShowCloseIcon(true).Width("335px").Visible(false).Content("Your details have been updated successfully, Thank you.").Target("#control_wrapper").IsModal(true).AnimationSettings(new DialogAnimationSettings() { Effect = DialogEffect.Zoom }).Render()
                    </div>
                </form>
            </div>


            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    debugger;
    $(function () {
        $("#btn").click(function (e) {
             
            var ageid = document.getElementById("Ageid").value;
            var formdata = new FormData($("#DocUploadForm")[0]);
            $.ajax({
                url: "@Url.Action("UploadDoc")",
                data: formdata,
                success: function (data) {
                    debugger;
                    UpdateDocsPartial(ageid)
                },
                type: 'POST',
                cache: false,
                contentType: false,
                processData: false
            });
            e.stopPropagation();
        });
    });
</script>

@Html.EJS().ScriptManager()








NP Narayanasamy Panneer Selvam Syncfusion Team July 28, 2019 06:43 PM UTC

Hi Adam, 
 
Sorry for the inconvenience. 
We are checking on this and we will update further on this in one business day (29/07/19). We will appreciate your patience until then. 
 
Regards, 
Narayanasamy P. 



NP Narayanasamy Panneer Selvam Syncfusion Team July 30, 2019 04:07 AM UTC

Hi Adam,

Thanks for your patience. 
 
We have validated your issue the reported scenario. In the shared code snippet, you did not configured the asyncSettings Property for saving and removing the file. So we suggest to enable the asyncSettings in your application. Then model will refreshed for every uploader and it returns the success message when uploader is successfully uploaded. 
Please find the code snippet below, 
@Html.EJS().Uploader("FileUpload").AutoUpload(false).Multiple(false).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Content("https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save"), RemoveUrl = @Url.Content("https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove") }).Render() 
 
If still the issue is persists kindly share the controller code. 
 
 
Regards, 
Narayanasamy P. 



UN Unknown July 31, 2019 01:32 AM UTC

I added the AsyncSettings as suggested and pointed the url to my controller method. It did pass the document and upload it successfully and return the successful message. However it does not pass any of the other form variables with it, so there are none of the values I also need to write to the database. So when I use my existing submit button, it does do everything but will not refresh the form or display message, when I use AsyncSettings I get the Clear and Sumbit button from that but it does not pass all form variables.

Here also is my method from my controller:

        [AcceptVerbs("Post")]
        public void UploadDoc()
        {
            var agencyID = Request["Ageid"];
            var agency = Request["Agency"];
            var title = Request["Title"];
            //var file = Request.Files["FileUpload"];
            var httpPostedFile = System.Web.HttpContext.Current.Request.Files["FileUpload"];
            // Save the files and values to the database here 
            if (httpPostedFile != null)
            {
                //var fileSave = System.Web.HttpContext.Current.Server.MapPath("docsdlstorage");
                var fileSave = ConfigurationManager.AppSettings["DocUpload"];
                var fileSavePath = Path.Combine(fileSave, httpPostedFile.FileName);
                if (!System.IO.File.Exists(fileSavePath))
                {
                    httpPostedFile.SaveAs(fileSavePath);
                    HttpResponse Response = System.Web.HttpContext.Current.Response;
                    Response.Clear();
                    Response.ContentType = "application/json; charset=utf-8";
                    Response.StatusDescription = "File uploaded succesfully";
                    Response.End();

                    docsdl newdoc = new docsdl();
                    newdoc.doc_class = Convert.ToInt32(agencyID);
                    newdoc.title = title;
                    newdoc.file_name = httpPostedFile.FileName;
                    newdoc.creation_dt = DateTime.Now;

                    db.docsdl.Add(newdoc);
                    db.SaveChanges();
                }
                else
                {
                    HttpResponse Response = System.Web.HttpContext.Current.Response;
                    Response.Clear();
                    Response.Status = "204 File already exists";
                    Response.StatusCode = 204;
                    Response.StatusDescription = "File already exists";
                    Response.End();
                }
            }
        }

Thank you again for any additional help you can provide.

Adam


NP Narayanasamy Panneer Selvam Syncfusion Team August 1, 2019 12:11 AM UTC

Hi Adam, 
 
Thanks for contacting us. 
 
We have checked your query. Yes, your suspected scenario is right. The additional values will not send to the controller. So in this case we suggest you to pass the additional values like AgeId and agency through args.customFormData in the uploading event as mentioned below, 
@cshtml 
@Html.EJS().Uploader("FileUpload").AutoUpload(false).Multiple(false).Uploading("onFileUpload").Success("onSuccess").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "http://localhost:61715/Home/Save", RemoveUrl = "http://localhost:61715/Home/Remove" }).Render() 
@script 
function onFileUpload(args) { 
    var Ageid = document.getElementById('Ageid').value; 
    var Agency = document.getElementById('Agency').value; 
    args.customFormData = [{ 'Id': Ageid }, { 'Agency': Agency} ]; 
} 
 
Receive this values in controller as mentioned below, 
var id = HttpContext.Request.Form["Id"];
var Agency = HttpContext.Request.Form["Agency"];
 
If need to refresh the value of the model after file has been successfully uploaded, we suggest taking the instances for the element and set value as null in the success event of uploader as mentioned below, 
 
@Html.EJS().Uploader("FileUpload").AutoUpload(false).Multiple(false).Uploading("onFileUpload").Success("onSuccess").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "http://localhost:61715/Home/Save", RemoveUrl = "http://localhost:61715/Home/Remove" }).Render() 
 
. . . . . . . 
 
<script> 
 
. . . . . . . 
    function onSuccess(args) { 
document.getElementById('Ageid').value = null; 
document.getElementById('Agency').value = null; 
} 
. . . . . . . . 
</script> 
 
Please find the sample from below link, 
 
 
Regards,  
Narayanasamy P.  


Loader.
Up arrow icon