This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 7 years ago.
I need post a uploades file and model, i use mvc this the code in the view:
function GuardarDocumento() {
var fileUpload;
var tipoDoc;
if (currentTabTitle == "#tab-AT") {
fileUpload = $("#inputFileAT").get(0);
tipoDoc = 'A';
}
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
var documento = {
Id_emd: 0,
Id_emm: {
Id_emm: id,
Tipo: tipo,
},
Tipo_emd: tipoDoc,
Fecha_emd: $("#txtFechaDocAT").val(),
Nombre_emd: $("#txtNombreDocAT").val(),
}
$.ajax({
url: "/Empleado/GuardarDocumento/" + JSON.stringify(documento),
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (data) {
if (data.success) {
alert("Documento Guardado con Éxito.");
Cancelar();
}
else {
alert(data.message);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
And the controller code:
[HttpPost]
public ActionResult GuardarDocumento(clsDocumentoEmpleadoModel documento)
{
try
{
if (Request.Files.Count > 0)
{
clsEmpleadoBLL bll = new clsEmpleadoBLL();
bll.PostedFile = Request.Files[0];
documento.Archivo_emd = Request.Files[0].FileName;
bll.AddDocument(documento);
}
else
{
return Json(new { success = false, message = "No ha seleccionado ningún archivo." });
}
}
catch (Exception ex)
{
GENException.Write(ex, "EmpleadoController.GuardarDocumento");
return Json(new { success = false, message = string.Format("Error: {0}", ex.Message) });
}
return Json(new { success = true, message = "Documento Guardado Correctamente." });
}
It does not work, bad request. If I put url: "/Empleado/GuardarDocumento/" + documento, i get into controller code but model is null.
What is wrong? I am trying send to controller both uploaded file and model, how can I do that?
The type that you're sending to the controller action must match the type the action is expecting. You're sending a FormData, and you're expecting a clsDocumentoEmpleadoModel.
Related
I need help with my ajax function. I have a form that submits data with the same input name
When I run my code without javascript, I can insert multiple input data with the same name,
Submitted structure
{"_token":"CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu","id":"7","service_name":["asfd","safd"]}
When I implement javascript, a concatenated string is sent to the controller and this makes the service_name inaccessible.
formdata:"_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=7&service_name%5B%5D=sdfg&service_name%5B%5D=gfds&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=8&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=9&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=10&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=11&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=18"
My javascript function
jQuery("form.ajax").on("submit", function (e) {
e.preventDefault();
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: $(".ajax#servicesForm").serialize()
},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function (jqXHR, exception) {
var msg = "";
if (jqXHR.status === 0) {
msg = "Not connect.\n Verify Network.";
} else if (jqXHR.status === 404) {
msg = "Requested page not found. [404]";
} else if (jqXHR.status === 500) {
msg = "Internal Server Error [500].";
} else if (exception === "parsererror") {
msg = "function Requested JSON parse failed.";
} else if (exception === "timeout") {
msg = "Time out error.";
} else if (exception === "abort") {
msg = "Ajax request aborted.";
} else {
msg = "Uncaught Error.\n" + jqXHR.responseText;
}
}
});
});
My PHP Controller Function
public function insert(Request $request)
{
return response()->json($request);
}
use FormData Object, to send fromdata
fd = new FormData();
fd.append("input-name", value1);
fd.append("input-name2", value2 OR arry of value);
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: fd
}
I found a workaround:
First, I created an array, and pushed all instances of input[name='service_name[]'] into the array.
Then I passed the data with ajax and was able to insert the data.
var serviceArray = new Array(), id;
jQuery.map($("input[name='service_name[]']"), function(obj, index) {
serviceArray.push($(obj).val());
});
My ajax script then:
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: 'post',
data: {
'service_name': serviceArray,
'id': id
},
dataType: 'JSON',
success: function(response) {
console.log(response);
}
});
Hi ihave this input with type file with multiple select enabled.
i need to get the files from the file input and pass it to my webmethod but i'm getting none in my webmethod, i've read that prop return a list, i have this code in jquery
function post_RepAttach(){
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:$('#FileUpload1').prop("files")[0]
}
var files = $('#FileUpload1').prop("files")[0];
alert(files);
$.ajax({
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Create-OCAP.aspx/post_attachment_rep',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
var response = data;
if (typeof callback != 'undefined') {
//hideLoadingGif();
//callback(response);
}
},
error: function (xhr, status, error) {
//hideLoadingGif();
console.log(xhr, status, error);
}
});
}
i have try this $('#FileUpload1').prop("files") remove the [0] but still no luck
and here's my webMethod
[WebMethod]
public static string post_attachment_rep(string Ocap_no, List<string> file_Name)
{
OcapDataAccess ODA = new OcapDataAccess();
bool result;
result = ODA.insert_reports(HttpContext.Current.Request.MapPath("~/OCAP/files/Reports/" + file_Name.ToString()), Ocap_no);
if (result == true)
{
return "1";
}
else
{
return "0";
}
}
but the file_Name count is zero even if i selected files
how can i achive it.
Hope you understand what i mean
var fileNames = $.map( $('#FileUpload1').prop("files"), function(val) { return val.name; });
and params is :
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:fileNames }
}
I have an ASP.NET MVC Application where I have a method, which returns a list of Objects:
public List<FileObject> GetAllFilesFromDirectory()
{
string filePath = #"C:\FilesToWatch";
string[] fileEntries = Directory.GetFiles(filePath, "*.txt", SearchOption.TopDirectoryOnly);
FileObject fo;
List<FileObject> list = new List<FileObject>();
foreach (var file in fileEntries)
{
FileInfo info = new FileInfo(file);
fo = new FileObject
{
FileName = info.Name, //asdf.txt
FilePath = info.FullName //C:\FilesToWatch\asdf.txt
};
list.Add(fo);
}
return list;
}
Now I want to return this list in javascript:
$.ajax({
type: "GET",
url: "Home/GetAllFilesFromDirectory",
data: ???,
success: function () {
console.log('success');
},
error: function () {
console.log('error');
},
complete: function (data) {
console.log('complete');
}
});
I know, that I have to add the data: attribute, but I do not really know, what I should write after data: to return this list.
You do not need to pass data as your controllerAction accepting no arguments. Here is more clear result you can return from your controllerAction as follow:
public ActionResult GetAllFilesFromDirectory()
{
string filePath = #"C:\FilesToWatch";
string[] fileEntries = Directory.GetFiles(filePath, "*.txt",
SearchOption.TopDirectoryOnly);
FileObject fo;
List<FileObject> list = new List<FileObject>();
foreach (var file in fileEntries)
{
FileInfo info = new FileInfo(file);
fo = new FileObject
{
FileName = info.Name, //asdf.txt
FilePath = info.FullName //C:\FilesToWatch\asdf.txt
};
list.Add(fo);
}
return Json(new { filesList = list }, JsonRequestBehaviour.AllowGet);
}
And then you can read the response in ajax as follow:
$.ajax({
type: "GET",
url: "Home/GetAllFilesFromDirectory",
success: function (resp) {
if(resp.filesList)
{
$.each(function( index, element ) {
console.log(element.FileName ); // i.e log the file name
});
}
},
error: function () {
console.log('error');
},
complete: function (data) {
console.log('complete');
}
});
I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.
Model:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
Controller:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
View:
<td><input class="id" type="checkbox" id=#item.ID /></td>
<td>#Html.DisplayFor(x => #item.ID)</td>
<td><input class="date" id=date#item.ID type="text" value='#item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
Any help would be appreciated!
I think you need contentType: 'application/json' in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model in your controller action.
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).
I have the following Javascript code contained on the click event of an upload button where I want to record an xAPI statement. I have put a breakpoint on my Admin/NewStatement method and although it is hitting it the page is always displaying the error message even before I have stepped through the breakpoint. Why is this failing all the time?
var postData = {
'userID': 1,
'verbID': 26,
'objectID':1
};
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "/Admin/NewStatement",
data: postData,
success: function (data) {
var json = data;
alert("THIS IS MY JSON" + json);
//tincan.sendStatement(json);
},
error: function (error) {
alert("An Error has occurred during the Creation of this xAPI Statement");
alert(error);
}
});
I have the following method at Admin/NewStatement
public string NewStatement(int userID, int verbID, int objectID)
{
string result;
result = avm.AddStatement(userID, verbID, objectID);
return result;
}
avm.AddStatement refers to my ViewModel code:
public string AddStatement(int userID, int verbID, int objectID)
{
Actor actor = actorRepository.Get(a => a.UserID == userID).FirstOrDefault();
Verb verb = verbRepository.Get(v => v.VerbID == verbID).FirstOrDefault();
StatementObject statementObject = statementObjectRepository.Get(o => o.StatementObjectID == objectID).FirstOrDefault();
Statement newStatement = new Statement();
newStatement.id = System.Guid.NewGuid();
newStatement.ActorID = actor.ActorID;
newStatement.VerbID = verb.VerbID;
newStatement.StatementObjectID = statementObject.StatementObjectID;
this.statementRepository.Add(newStatement);
this.statementRepository.SaveChanges();
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ObjectCreationHandling = ObjectCreationHandling.Auto;
var json = JsonConvert.SerializeObject(newStatement);
return json.ToString();
}