Upload file with form using jQuery Ajax in ASP.Net Core MVC

pandeygolu4200
 
on Sep 15, 2022 03:54 AM
423 Views

I need to upload form data along with file from razor view, how can i upload it from Ajax call ?

Please refer my code, i am trying to upload but using Ajax but it got error while passing values.

<form class="tab-pane" id="step2" enctype="multipart/form-data">
    <div class="provider-details-wrapper">
        <h6>License, Certifications & Documents</h6>
        <div class="row">
            <div class="col-lg-3 col-md-4">
                <div class="form-group">
                    <label for="doctype">Document Type</label>
                    <select class="form-control form-select" id="DocumentTypeID" name="DocumentTypeID">
                    </select>
                </div>
            </div>
            <div class="col-lg-3 col-md-4">
                <div class="form-group">
                    <label for="firstname">Document Name</label>
                    @Html.TextBoxFor(c=>c.ManageProviderDocument.DocumentName,new{ @class="form-control",id="documentname"})
                    <span asp-validation-for="ManageProviderDocument.DocumentName" class="text-danger"></span>
                    @* <input type="text" class="form-control" id="firstname">*@
                </div>
            </div>
 
            <div class="col-lg-3 col-md-4">
                <div class="form-group">
                    <label for="firstname">Document Number</label>
                    @Html.TextBoxFor(c=>c.ManageProviderDocument.DocumentNumber,new{ @class="form-control",id="documentnumber"})
                    <span asp-validation-for="ManageProviderDocument.DocumentNumber" class="text-danger"></span>
                    @*   <input type="text" class="form-control" id="documentnumber">*@
                </div>
            </div>
 
            <div class="col-lg-3 col-md-4">
                <label for="state">State</label>
                <div class="form-group">
                    <select class="form-control form-select" id="DocStateID">
                    </select>
                </div>
            </div>
            <div class="col-lg-3 col-md-4">
                <div class="form-group">
 
                    <label for="isuuedate">Isuue Date</label>
                    @Html.TextBoxFor(c => c.ManageProviderDocument.IssueDate, new { id = "isuuedate",type = "date",@class="form-control" })
                    <span asp-validation-for="ManageProviderDocument.IssueDate" class="text-danger"></span>
                    @* <input type="date" class="form-control" id="isuuedate">*@
                </div>
            </div>
            <div class="col-lg-3 col-md-4">
                <div class="form-group">
                    <label for="tax">Expiration Date</label>
                    @Html.TextBoxFor(c => c.ManageProviderDocument.ExpirationDate, new { id = "eradate",type = "date",@class="form-control" })
                    <span asp-validation-for="ManageProviderDocument.ExpirationDate" class="text-danger"></span>
                    @*  <input type="date" class="form-control" id="tax">*@
                </div>
            </div>
 
        </div>
        <div class="row">
            <div class="col-xl-12 col-lg-12 col-md-12 mt-3">
 
                <input type="file" id="fileUpload" class="fileUpload">
                <button id="btnUpload" class="btn btn-success">Upload</button>
                @* <button class="btn disabled-btn me-3 mb-2">Drag file here, or Click to
                Upload</button>*@
                <button class="btn upload-btn px-5">Upload</button>
            </div>
        </div>
        <div class="d-flex justify-content-end mt-5">
            <a href="manage-provider.html" class="btn cancel-btn me-3">Back</a>
            <a href="manage-provider.html" class="btn save-btn">Save & next</a>
        </div>
    </div>
</form>

this is my ajax call getting failed at line 

var form = $('#step2')[0];

function validationFormStepTwo()
{
    if (!$("#step2").valid()) {
        return false;
    }
}
$("#btnUpload").on('click',function(e){
     
      e.preventDefault();
      validationFormStepTwo();  
        var fdata = new FormData();
 
        //var fileInput = $('#step2')[0];
        //var file = fileInput.files[0];
        //fdata.append("File", file);
        alert('hi')
           var form = $('#step2')[0];
                    
                    var formData = new FormData(form);
                var form = $('#step2');
 
                var formData = new FormData(form);
 
        // You can update the jquery selector to use a css class if you want
        //$("input[type='text'").each(function (x, y) {
        //    fdata.append($(y).attr("name"), $(y).val());
        //});
 
   $.ajax({
        type: "POST",
        url: '@Url.Action("AddProvider","Provider")',
        contentType: false,
        processData: false,
        data: fdata,
        success: function (message) {
            alert(message);
        },
        error: function () {
            alert("There was error uploading files!");
        }
    });
});

 

[HttpPost]
public IActionResult AddProviderDocument(ProviderViewModel model)
{
    ModelState.Remove("ManageProviderModel");
    if (ModelState.IsValid)
    {
        ManageProviderDocumentModelCopy modeldoc = new ManageProviderDocumentModelCopy();
        modeldoc.DocumentTypeID = model.ManageProviderDocument.DocumentTypeID;
        modeldoc.DocumentName = model.ManageProviderDocument.DocumentName;
        modeldoc.DocumentNumber = model.ManageProviderDocument.DocumentNumber;
        modeldoc.StateID = model.ManageProviderDocument.StateID;
        modeldoc.IssueDate = model.ManageProviderDocument.IssueDate;
        modeldoc.ExpirationDate = model.ManageProviderDocument.ExpirationDate;
        
        AccountApiCall accountApiCall = new AccountApiCall(Configuration["PrescriptionAPI"]);
        var Response = accountApiCall.PostAPIcall<GetProviderDetailModel>(model, "provider/documentadd", HttpContext.Request.Cookies["Token"].ToString());
        //return Json(Response.message);
        if (Response.status)
        {
            ViewBag.ProviderId = Response.data;
            return View(); 
        }
        else
        {
            ModelState.AddModelError("CustomError", Response.message);
            return View();
        } 
    }
    else
    {
        return View();
    }

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 15, 2022 03:58 AM
pandeygolu4200
 
on Sep 15, 2022 04:39 AM

Thanks for your answer but i am using form to submit my data along with file.

The problem i am getting like when i post FormData in my Ajax call, file and state and documentype data is getting null in model.

[HttpPost]
public IActionResult AddProviderDocument(ProviderViewModel model)
{
    ModelState.Remove("ManageProviderModel");
    if (ModelState.IsValid)
    {
        ManageProviderDocumentModelCopy modeldoc = new ManageProviderDocumentModelCopy();
        modeldoc.UserID = Convert.ToString(TempData["ProviderId"]);
        modeldoc.DocumentTypeID = model.ManageProviderDocument.DocumentTypeID;
        modeldoc.DocumentName = model.ManageProviderDocument.DocumentName;
        modeldoc.DocumentNumber = model.ManageProviderDocument.DocumentNumber;
        modeldoc.StateID = model.ManageProviderDocument.StateID;
        modeldoc.IssueDate = model.ManageProviderDocument.IssueDate;
        modeldoc.ExpirationDate = model.ManageProviderDocument.ExpirationDate;

        AccountApiCall accountApiCall = new AccountApiCall(Configuration["PrescriptionAPI"]);
        var Response = accountApiCall.PostAPIcall<GetProviderDetailModel>(model, "provider/documentadd", HttpContext.Request.Cookies["Token"].ToString());
        //return Json(Response.message); 
        if (Response.status)
        {
            ViewBag.ProviderId = Response.data;
            return View();
        }
        else
        {
            ModelState.AddModelError("CustomError", Response.message);
            return View();
        }
    }
    else
    {
        return View();
    }
}

this is my ajax

function validationFormStepTwo()
{
    if (!$("#step2").valid()) {
        return false;
    }
}
$("#btnUpload").on('click',function(e){    
      e.preventDefault();
    validationFormStepTwo();      
         var form = $('#step2')[0];
                   
        var formData = new FormData(form);
          // formData.append("fileName", $("#fileName").val());

            
            formData.append("file", $("#fileUpload")[0].files[0]);
                formData.append("StateID", $("#DocStateID").val());
                 formData.append("DocumentTypeID", $("#DocumentTypeID").val());
               
        alert('hi')
           
      

   $.ajax({
        type: "POST",
        url: '@Url.Action("AddProviderDocument","Provider")',
        contentType: false,
        processData: false,
        data: formData,
        success: function (message) {
            alert(message);
        },
        error: function () {
            alert("There was error uploading files!");
        }
    });
});

 

dharmendr
 
on Sep 15, 2022 09:06 AM

To get uploaded Files use Form Collection in Controller Action method.

IFormFile file = Request.Form.Files["file"];