Parameswaran R

Parameswaran R

  • NA
  • 254
  • 6.5k

How to send data & file by json and Ajax to Controller Mvc?

Dec 16 2016 7:33 AM
jQuery:-

$(document).on("click", ".save-visa-details", function (e) 
{     
e.preventDefault(); 
var json_obj = { "visa": [] };     
$(".table .js-visa").each(function (index, element) { 
var row = $(this).attr("data-row"); 
if (typeof row != "undefined" && row != "") {
 var visajsonObject = { "employee_id": "", "visa_country": "", "visa_type": "", "visa_entrytype": "", "visa_startdate": "", "visa_expiredate": "", "visa_copy": "" }; 
visajsonObject.employee_id = 454543; var fileInput = new FormData($(".js-course-" + row + " .js-visa-copy").get(0));   
jsonObject.visa_copy = fileInput;             
 visajsonObject.visa_country = $(".js-visa-" + row + " .country").val();  

visajsonObject.visa_type = $(".js-visa-" + row + " .visatype").val(); 
visajsonObject.visa_entrytype = $(".js-visa-" + row + " .visamemberentrytype").val();    
visajsonObject.visa_startdate = $(".js-visa-" + row + " .js-visa-start-date").val();
visajsonObject.visa_expiredate = $(".js-visa-" + row + " .js-visa-expire-date").val(); 
json_obj.visa.push(visajsonObject); } });  
    $.ajax({  
 type: "POST",    
  url: "@Url.Action("SaveEmployeeVisa")",    
 dataType: "json", 
 contentType: "application/json; charset=utf-8",    
 data: JSON.stringify(json_obj),  
 success: function (data) {        
 alert("Visa details are register successfully"); }
 });
  });
Model
public class Visa {
public int employee_id { get; set; } 
public string visa_country { get; set; }
public string visa_type { get; set; } 
public string visa_entrytype { get; set; } 
public DateTime? visa_startdate { get; set; } 
public DateTime? visa_expiredate { get; set; } 
public HttpPostedFileBase visa_copy { get; set; } 
}

Controller:
[HttpPost] 
public ActionResult SaveEmployeeVisa(List<Visa> visa) 
if (_cm.SaveEmployeeVisaDetails(visa)) 
{ return Json(""); 
else 
eturn Json("Not saved, Went to some bug");
 }  
}



Answers (1)