I try to save a file (image) on C# MVC and JS with the following function js
function Add() {
var data = new FormData();
var files = $("#txtUploadFile").get(0).files;
var cod = document.getElementById('cod').value;
var mat = document.getElementById('mat').value;
var status = document.getElementById('status').value;
var plant = document.getElementById('plant').value;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
data.append("mat", mat);
data.append("status", status);
data.append("plant", plant);
data.append("code", cod);
}
$.ajax({
type: 'POST',
url: '/Pred/Admin/AddPred',
contentType: false,
processData: false,
data: data,
success: function (response) {
if(response.msg == 1)
{
refreshTable(response.data);
}
alert('Predio agregado.');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
}
}
}
and on the codebehind I used it
public ActionResult AddPred()
{
int isInsert=0;
string route = ConfigurationManager.AppSettings["MAPS_ROUTE"];
string[] status, plants, mats, codes;
int stat;
try
{
var requeststatus = Request.Params;
status = requeststatus.GetValues("status");
plants = requeststatus.GetValues("plant");
codes = requeststatus.GetValues("cod");
mats = requeststatus.GetValues("mat");
if (status[0] == "On")
stat= 1;
else
stat= 0;
string plant = plants[0];
string mat = mats[0];
string code = codes[0];
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath(route), fileName);
path = Server.MapPath(route) + fileName;
var sqlpath = "." + route + "/" + fileName;
fileContent.SaveAs(path);
isInsert = ma.InsertPred(code, mat, stat, plant, sqlpath);
}
}
merge.preds = ma.GetPreds();
return Json(new { success = true, data = merge.preds, msg = isInsert }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("add failed");
}
}
But the server response ever is
POST myserver/Preds/Admin/AddPred 500 (Internal Server Error)
and I used console.log but I can't to get the error information, When used this code on local side, it's runs Okey, save the image and return model for refresh the front, but when put the aplication on the server, only return error, others funtions works (modal show, return model with json) but doesn't work save a image, I set permissions (write, load, modify) on the server folder,
someone give a idea for solves this problem, I don't know whats wrong
Try like this :
function getCities(id) {
$.ajax({
type: "POST",
url: "#Url.Action("Index", "Default")",
data: '{id: id }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert(response.responseData);
window.location = '/Default/YourView';//
},
error: function (response) {
alert("error!"); //
}
});
}
//In your controller
public JsonResult Index(string id)
{
merge.country= mp.Country();
merge.city= mp.City(id);
return Json("you can return an object or a string, what you want");
}
Related
I was trying to get the base64 post in my codebehind webmethod,
but it seems like everytime I include the base64 I get an error : the server responded with a status of 500 (Internal Server Error) - it keeps on hitting the error function.
The Post works with the other strings when the base64 is not inlcuded int the data that im passing.
function event_create() {
alert("alert test : function works => onclick");
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var eventTitle = $("#eventTitle").val();
var eventDesc = $("#eventDesc").val();
var eventTimeStart = $("#eventTimeStart").val();
var eventTimeEnd = $("#eventTimeEnd").val();
var eventDateStart = $("#eventDateStart").val();
var eventDateEnd = $("#eventDateEnd").val();
var eventType = $("#eventType").val();
var eventPlace = $("#eventPlace").val();
var eventAttendee = document.getElementById("lblSelected").innerText;
var userID = sessionStorage.getItem("userID");
var imageBase64 = getBase64(document.getElementById('test').files[0]);
var data = { 'eventTitle': eventTitle, 'eventDesc': eventDesc, 'eventPlace': eventPlace, 'eventType': eventType, 'eventAttendee': eventAttendee, 'userID': userID, 'imageBase64': imageBase64};
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
url: ".../../../../Operation/insert.aspx/createEvent",
data: JSON.stringify(data),
datatype: "json",
success: function (result) {
if (result.d <= 0) {
//false alert something
alert("FALSE");
}
else if (result.d > 0) {
//true
alert(result.d);
}
else {
alert("sent but no call-back");
}
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" connection to the server failed ");
console.log("error: " + errorthrown);
}
});
}
Here's the Webmethod that will get the post
[WebMethod(EnableSession = true)]
public static string createEvent(string eventTitle, string eventDesc, string eventPlace, string eventType, string eventAttendee, string userID, string imageBase64)
{
String orgID = (String)HttpContext.Current.Session["orgID"];
string response = orgID;
string path = HttpContext.Current.Server.MapPath("~/Users/Organizer/organizerData/"); // de path
//Check if directory exist
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = "event1" + ".jpg";// for instance
//set the image path
string imgPath = Path.Combine(path, imageName);
byte[] imageBytes = Convert.FromBase64String(imageBase64);
File.WriteAllBytes(imgPath, imageBytes); //write the file in the directory
return imageBase64;
}
I am trying to do some Get_Data from dataBase Using asynchronous ajax request and WebMethod
Everything works fine , but when i want the returned value from my web method value , i got undefined value
I Know That this question is asked before
I have tried almost all advices to achieve my wanted goal , but unfortunately nothing happened .
Create Instance Outside the function than set it to the return value.
Set The dataType:"Json"
Create an instance inside the function and set it to empty string
var ReturnValue="";
Let Json object stringify my returned value
and many other steps
So please do not mark my question as duplicated value
Here is my code below :
//Javascript and Jquery Codes
$(document).ready(function() {
$("#PValidateLogin").hide();
});
function killSpaces(element) {
var characters = element.toString();
var resultText = "";
for (var i = 0; i < characters.length; i++) {
if (!(characters[i] == " ")) {
resultText += characters[i];
}
}
return resultText;
}
$("#<%=btnLogin.ClientID%>").click(function() {
var MyWantedhref;
var Result = ValidateMyLogin();
if (typeof Result === "undefined") {
alert("Something wrong with codes");
} else if (Result == "false" || killSpaces(Result).length == 0) {
alert("wrong user ");
} else {
MyWantedhref = "/Frm_Manager/frm_MenuCategory.aspx";
location.replace(MyWantedhref);
}
});
function ValidateMyLogin() {
var ReturValue;
var UserName = $("#<%=txtUserName.ClientID%>").val();
var Password = $("#<%=txtUserPassword.ClientID%>").val();
if (killSpaces(Password).length >= 4 && killSpaces(UserName).length >= 4) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
url: "frm_ValidateLogin.aspx/ValidateLogin",
data: "{'UserName':'" + UserName + "','Password':'" + Password + "'}",
success: function(data) {
ReturValue = data.d;
},
error: function(err) {
ReturValue = err.d;
}
});
}
return ReturValue;
}
And Here are the C# Code
<code>
private static OwnerAccountBO _OwnerAccountBO;
public static OwnerAccountBO OwnerAccountBO { get { return new OwnerAccountBO(); } set { _OwnerAccountBO = value; } }
[WebMethod(EnableSession = true)]
public static string ValidateLogin(string UserName, string Password)
{
string CharResult = "";
object[] UserParameters = { UserName, Password };
int Result = OwnerAccountBO.validateLogin(UserParameters);
if (Result > 0)
{
HttpContext.Current.Session["OwnerAccountID"] = Result;
CharResult += Convert.ToString(Result);
}
else
{
CharResult += "false";
}
return CharResult;
}
</code>
Please Any Help would be thankful .
And of course i want a proper explication for the wrong action or flow that i am doing to have such error
You returned a string value from the method
string CharResult = "";
object[] UserParameters = { UserName, Password };
int Result = OwnerAccountBO.validateLogin(UserParameters);
if (Result > 0)
{
HttpContext.Current.Session["OwnerAccountID"] = Result;
CharResult += Convert.ToString(Result);
}
else
{
CharResult += "false";
}
return CharResult;
so in you ajax it must be received like this
$.ajax({
success: function (data)
{
ReturValue = data; //fixed it with this
}
});
Not
$.ajax({ success: function (data)
{
ReturValue = data.d; //issue here
},
error: function (err)
{
ReturValue = err.d;
}
});
Error provide that input string was not in correct format in this line:
objproject.CategoryStatus(Convert.ToInt32(Id), true);
This is my aspx code:
[WebMethod]
public static void ActivateSelected(String Id)
{
clsCategoryBL objproject = new clsCategoryBL();
string[] arr = Id.Split(',');
foreach (var id in arr)
{
if (!string.IsNullOrEmpty(id))
{
objproject.CategoryStatus(Convert.ToInt32(Id), true);
}
}
}
This is my jQuery bind code:
function ActivateSelected()
{
var ids = '';
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
debugger;
for (var i in cells) {
var inputArray = cells[i].getElementsByTagName('input');
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].type == 'checkbox' && inputArray[i].checked == true) {
debugger;
ids += inputArray[i].id + ',';
}
}
}
debugger;
var urldata = "WebForm5.aspx/ActivateSelected";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
url: urldata,
data: "{Id:'" + ids + "'}",
success: function (dt)
{
debugger;
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
//console.log();
//alert(result);
}
});
}
This is my BL Class:
public string CategoryStatus(int CategoryID, bool Status)
{
using (KSoftEntities db = new KSoftEntities())
{
try
{
var ProjectDetails = db.tblCategories.Where(i => i.CategoryID == CategoryID).ToList();
ProjectDetails[0].Status = Status;
db.SaveChanges();
if (Status == true)
return "Record Activated successfully";
else
return "Record deactivated successfully";
}
catch (Exception ex)
{
}
return "Error on updation";
}
}
The Last ID is attached with extra comma,
Like : "1234,123,12345,"
spliting string of above example will create array of 4 elements, having empty string in last element. Thats why its Throwing error.
You need to handle the ids += inputArray[i].id + ','; in jquery.
here you can check whether the id is last id in the list and does that require comma after that.
function ActivateSelected()
{
var ids = '';
var cells = Array.prototype.slice.call(document.getElementById("example1").getElementsByTagName('td'));
debugger;
for (var i in cells) {
var inputArray = cells[i].getElementsByTagName('input');
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i].type == 'checkbox' && inputArray[i].checked == true) {
debugger;
ids += inputArray[i].id + ',';
}
}
}
ids = ids.substring(0,ids.lastIndexOf(','));
debugger;
var urldata = "WebForm5.aspx/ActivateSelected";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
url: urldata,
data: "{Id:'" + ids + "'}",
success: function (dt)
{
debugger;
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
//console.log();
//alert(result);
}
});
}
I've currently got some working code that will upload a document to the App_data file, however I need to be able to differentiate the files uploaded if they have the same name. I want to do this by modifying the file name like so: ID" "Filename
I've had a few attempts to include this in the object thats passed to the controller but I can't find it stored anywhere (I presume that it gets stripped out when being passed?).
Here is my current code:
var files = $('#txtUploadFile')[0].files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
}
// data.uploadName = task.Id + " " + files[0].name;
// File.filename = Id + " " + file.filename;
$.ajax({
type: "POST",
url: '../Document/UploadFiles/',
contentType: false,
processData: false,
//data: {'id': (nextRef + 1), 'fileLocation': files[0].name }, // THIS DOESN'T WORK
data: data, // THIS WORKS WITHOUT ANY OTHER VARIABLES
dataType: "json",
success: function (result) {
//alert(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
alert(log(err));
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}
[HttpPost]
public JsonResult UploadFiles()//string id, string fileLocation)
{
try
{
foreach (string file in Request.Files)
{
var hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = Path.GetFileName(file);
var path = Path.Combine(Server.MapPath("~/App_Data/"), Path.GetFileName(hpf.FileName));
// Save the file
hpf.SaveAs(path);
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return this.Json("Upload failed");
}
return this.Json("File uploaded successfully");
}
change from url: '../Document/UploadFiles/', to url: '#Url.Action("UploadFiles","YourController")
and in your controller
public class YourController:Controller{
[HttpPost]
publiction ActionResult UploadFiles(){
if (Request.Files != null && Request.Files.Count > 0)
{
string path=Server.MapPath("~/App_Data");
Request.Files[0].SaveAs(path + fileName);
return Json("File uploaded","text/json",JsonRequestBehavior.AllowGet);
}
return Json("No File","text/json",JsonRequestBehavior.AllowGet);
}
}
your html should be
<div><input type="file" name="UploadFile" id="fileupload" Class="fileupload" />
</div>
your ajax call should be
$.ajax({
type: "POST",
url: '/MyController/UploadFiles?id=' + myID,
contentType: false,
processData: false,
data: data,
success: function(result) {
console.log(result);
},
error: function (xhr, status, p3, p4){
});
//and your controller
[HttpPost]
public JsonResult UploadFiles(string id)
{
// whatever you want to that id
}
Happy coding...
I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.
function CallMethodTest(Id) {
//alert(Id);
$.ajax({
type: 'POST',
url: '/MyController/MyMethod',
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: "{'Id': '" + Id + "'}",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
[System.Web.Services.WebMethod]
public string MyMethod()
{
return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
return "1"; // Works fine
}
As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.
From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"
If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult
[HttpPost]
public ActionResult MyMethod(){
return Json("ABC");
}
Also, if you are ever going to call a method in your controller via GET then use
public ActionResult MyMethod(){
return Json("ABC", JsonRequestBehavior.AllowGet);
}
In View You use the following code,
function ItemCapacity() {
$.ajax({
type: "POST",
url: '#Url.Action("ItemCapacityList", "SalesDept")',
data: { 'itemCategoryId': itemCategoryIds },
dataType: 'json',
cache: false,
success: function (data) {
var capacityCounter = 0;
var capacitySelected = "";
for (var i = 0; i < rowsCount; i++) {
var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
var categoryId = $(tr).find('td:eq(5)').text();
var isSelectOrNot = $(tr).find('td:eq(1)').find('select');
if (isSelectOrNot.is('select')) {
$.map(data, function (item) {
if (categoryId == item.ItemCategoryID) {
isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
capacityCounter = capacityCounter + 1;
capacitySelected = item.ItemCapacityID;
}
});
if (capacityCounter == 1) {
isSelectOrNot.val(capacitySelected);
}
capacityCounter = 0;
capacitySelected = "";
}
}
},
error: function () { alert("Connection Failed. Please Try Again"); }
});
}
}
In the Controller Use the following Code,
public JsonResult ItemCapacityList(string itemCategoryId)
{
List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();
string[] itemCategory = itemCategoryId.Split('#');
int itemCategoryLength = itemCategory.Length, rowCount = 0;
string itemCategoryIds = string.Empty;
for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
{
itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
}
itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);
lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);
return new JsonResult { Data = lsItemCapacity };
}