Formdata empty on Controller even after calling append - ajax

On browse button click I have appended file(images) in FormData
and on Add Product button click I have to post Formdata via ajax to controller
but I am getting FromData as null on controller as well as on console.log.
Please let me know where I am going wrong.
Browse Button Click Event
$(document).ready(function () {
var _formData = new FormData();
$('.Btn_Browse').on('click', function () {
let input = document.createElement('input');
input.setAttribute('id', 'input_image')
input.setAttribute('multiple', 'multiple');
input.type = 'file';
input.onchange = _ => {
let files = Array.from(input.files);
if (files.length > 1) {
for (var i = 0; i < files.length; i++) {
_formData.append(files[i].name, files[i]);
}
};
input.click();
});
});
Add Product Button Click Event
$('#id_AddProduct').click(function (e) {
for (var key of _formData.entries()) {
console.log(key[0] + ', ' + key[1]);
}
$.ajax({
type: "POST",
url: "AddProduct",
contentType: false,
processData: false,
cache: false,
data: _formData,
success: function (response) {
},
failure: function (response) {
confirm("Your process is failed..");
},
error: function (response) {
confirm("Error occur during the process..");
}
});
});
Controller
public ActionResult AddProduct()
{
byte[] imagebyte = null;
int count = Request.Files.Count;
HttpFileCollectionBase Files = Request.Files;
for (int i = 0; i < Files.Count; i++)
{
HttpPostedFileBase httpPostedFileBase = Files[i];
if (httpPostedFileBase != null)
{
List<DALImage> imageList = new List<DALImage>();
if (Request.Files.Count > 0)
{
using (var br = new BinaryReader(httpPostedFileBase.InputStream))
{
var imgdata = br.ReadBytes(httpPostedFileBase.ContentLength);
DALImage objImg = new DALImage();
objImg.ImageName = httpPostedFileBase.FileName;
objImg.ImageTye = httpPostedFileBase.ContentType;
objImg.ImageData = Convert.ToBase64String(imgdata);
imageList.Add(objImg);
}
}
}
//string message = DAL.AddProduct(imageList, objProductDetails);
}
return Json(imagebyte, JsonRequestBehavior.AllowGet);
}

Related

Populate One Dropdown on selection of other -MVC

I am trying to populate one dropdown list based on the selection of other dropdown list. This is what I have till now.
My Controller:
[HttpPost]
public JsonResult LoadReasonsByCategory(string resId)
{
var queryy = from item in db.T_SD_CD_GROUP
where resId.Contains(item.SCG_CD_TYPE)
select new
{
item.SCG_CD_TYPE,
item.SCG_CD_DESC
};
var ObjList = new List<SelectListItem>();
foreach (var item in queryy)
{
ObjList.Add(new SelectListItem() { Text = item.SCG_CD_DESC.ToString(), Value = (item.SCG_CD_TYPE) });
}
return Json(ObjList, JsonRequestBehavior.AllowGet);
}
JS
$("#ddlReasonCategory").on('change', function () {
var item = $(this).find("option:selected");
var value = $("#ddlReasonCategory").val(); //get the selected option value
//var text = item.html(); //get the selected option text
//alert(item.val());
$.ajax({
url: '/CRActual/LoadReasonsByCategory',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ resId: value}),
success: function (data) {
alert("sUccess");
$("#ddlReasonType").html("");
ddlReasonType.append($('<option></option>').val("").html("Please select a City"));
for (var i = 0; i < data.length; i++) {
ddlReasonType.append($('<option></option>').val(data[i].Text).html(data[i].Text));
}
},
error: function () {
alert("Fail")
},
});
View:
#Html.DropDownList("ddlReasonCategory", (IEnumerable<SelectListItem>)ViewBag.ddlReasonCategory, new { #class = "chosen-select col-md-3", #data_placeholder = "Please select" })
#Html.DropDownList("ddlReasonType", new SelectList(string.Empty, "Value", "Text"), "Please select a Reason", new { #class = "chosen-select col-md-3", #data_placeholder = "Please select" })
The codes runs absolutely without any errors, but the second drop down binding fails. Where am I going Wrong?
If your LoadReasonsByCategory method returns data correctly then write the success function code in the Ajax as follows:
success: function (data) {
var ddlResonTypeSelector = $("#ddlReasonType");
ddlResonTypeSelector.empty();
if (data.length > 0) {
ddlResonTypeSelector.append($("<option>").val("").text("Please select a Reason Type"));
$(data).each(function(index, item) {
ddlResonTypeSelector.append($("<option>").val(item.value).text(item.text));
});
} else {
ddlResonTypeSelector.append($("<option>").val("").text("Reason Type List is empty!"));
}
},

Json result returned as a file in Internet Explorer?

net MVC application, in which I have multiple charts. On these charts, I have applied filters and by clicking each filter, I do an ajax call which returns the result in Json and then applies to the charts.
Now its working perfectly in Firefox and Chrome, but in Internet Explorer - Ajax call is always unsuccessful. I tried hitting the web api url directly through my browser and the issue it seems is, the result json was being returned as a file to be downloaded.
This is my ajax code :
function getIssueResolvedGraphdata(control, departCode, departName) {
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var resolvedStartDate = myData.data.IssueResolvedStartDate;
var issueData = myData.data.IssueData;
var resolveData = myData.data.ResolvedData;
//converting issueData into integer array...
var issue = issueData.replace("[", "");
var issue1 = issue.replace("]", "");
var issue2 = issue1.split(",");
for (var i = 0; i < issue2.length; i++) { issue2[i] = parseInt(issue2[i]); }
//converting resolvedData into integer array
var resolve = resolveData.replace("[", "");
var resolve1 = resolve.replace("]", "");
var resolve2 = resolve1.split(",");
for (var j = 0; j < resolve2.length; j++) { resolve2[j] = parseInt(resolve2[j]); }
//getting max value from array...
var issueMaxVal = Math.max.apply(null, issue2);
var resolveMaxVal = Math.max.apply(null, resolve2);
//Eliminating leading zeros in issue array
var removeIndex = 0;
var myDate;
var newDate;
var arrayLength;
if (issueMaxVal != 0) {
arrayLength = issue2.length;
for (var i = 0; i < arrayLength; i++) {
if (issue2[0] == 0) {
issue2.splice(0, 1);
removeIndex = i;
} else {
break;
}
}
//Getting days count of current month
var monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
var monthEnd = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
var monthDays = 0;
if (monthLength == 28) {
monthDays = removeIndex;
}
else if (monthLength == 30) {
monthDays = removeIndex + 1;
}
else if (monthLength == 31 || monthLength == 29) {
monthDays = removeIndex + 2;
}
//matching the resultant issue array with resolve array & setting start date
var iDate = resolvedStartDate;
var tDate = '';
for (var i = 0; i < iDate.length; i++) {
if (iDate[i] == ',') {
tDate += '/';
}
else {
tDate += iDate[i];
}
}
if (removeIndex != 0) {
resolve2.splice(0, (removeIndex + 1));
var myDate = new Date(tDate);
myDate.setDate(myDate.getDate() + monthDays);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
} else {
var myDate = new Date(tDate);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
}
} else {
alert("Empty");
}
//updating chart here...
var chart = $('#performance-cart').highcharts();
chart.series[0].update({
pointStart: newDate,
data: issue2
});
chart.series[1].update({
pointStart: newDate,
data: resolve2
});
if (issueMaxVal > resolveMaxVal) {
chart.yAxis[0].setExtremes(0, issueMaxVal);
} else {
chart.yAxis[0].setExtremes(0, resolveMaxVal);
}
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
} });}
Code from web api controller :
[HttpGet]
[CrossDomainActionFilter]
public Response<GraphIssueResolvedWrapper> GetQueryIssueResolvedData(string deptCode)
{
Response<GraphIssueResolvedWrapper> objResponse = new Response<GraphIssueResolvedWrapper>();
GraphIssueResolvedWrapper objGraphIssueResolvedWrapper = new GraphIssueResolvedWrapper();
try
{
....code.....
objResponse.isSuccess = true;
objResponse.errorDetail = string.Empty;
objResponse.data = objGraphIssueResolvedWrapper;
}
catch (Exception ex)
{
objResponse.isSuccess = false;
objResponse.errorDetail = ex.Message.ToString();
objResponse.data = null;
}
return objResponse;
}
Reponse Class :
public class Response<T>
{
public bool isSuccess { get; set; }
public string errorDetail { get; set; }
public T data { get; set; }
}
I am stuck at this for hours now. Any help will be appreciated.
I have solved my problem by using the following code : ( I guess it needed CORS support)
function isIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
if (msie > 0)
return true;
return false;
}
Then in document.ready function of my binding script :
$(document).ready(function () {
if (isIE())
$.support.cors = true;
});
Note : it still download Json stream as a file but now my AJAX call is successful upon each hit.
You've missed contentType: 'text/html' which is pretty important for IE7-8:
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
contentType: 'text/html'
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var result = JSON.parse(myData);
///...code...
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
To make it works in IE7-8 you also need to be sure that you've writing Conrent-Type Header into your response on server side. Add this line right before return statement;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html; charset=iso-8859-1");
And in code probably you will need to parse result in success method by using JSON.parse(myData);

Passing AJAX request in MVC3 environment

I was using MVC3 with AJAX. I was using AJAX within another AJAX. For the first AJAX request, it properly sends to the controller with data. But after returning from the AJAX request, I again posting the same data to another action. But second time the data comes null when coming to the controller. Please help me to fix this issue.
Code
$(document).ready(function () {
$('.deleteitems').live('click', function (e) {
var items = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items.push($(this).attr("Id"));
});
var json = JSON.stringify(items);
var perm = $("#Permission").val();
if (items.length != 0) {
if (perm == "True") {
$.ajax({
url: '/ItemControl/ItemControl/Catalogue_Check',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data == "S") {
DelBibsAlso();
}
else {
DelItemsonly();
}
}
});
}
else {
$("#divMes").removeClass("Success");
$("#divMes").addClass("Error");
showError("Sorry you dont have Permission!");
}
}
else {
alert("Select any Items to delete");
e.preventDefault();
}
});
});
function DelItemsonly() {
var items2 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items2.push($(this).attr("Id"));
});
var itemjson = JSON.stringify(items2);
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": itemjson, "DelBib": 0 },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
function DelBibsAlso() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
var bibjson = JSON.stringify(items1);
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": bibjson, "DelBib": cond },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
Controller Code
public ActionResult Catalogue_Check(string[] id)
{
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
var Matched_BibID = (from asd in Db.Items
where ints.Contains(asd.Id)
select asd.BibId).ToList();
foreach (var idd in ints)
{
var bibid = (from bib in Db.Items where bib.Id == idd select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
return Json("S", JsonRequestBehavior.AllowGet);
}
}
return Json("N", JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteItems(string[] id, int? DelBib)
{
//var newid = id.Split(',');
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
foreach (var a in id)
{
int sel = Convert.ToInt32(a);
Item item = Db.Items.Single(i => i.Id == sel);
int Sess = Convert.ToInt16(Session["AccId"]);
string AdminName = User.Identity.Name;
bool Exist = Db.RouteOuts.Any(itm => itm.ItemId == item.Id);
if (!Exist)
{
weed.DeleteIt(item, Sess, AdminName);
var bibid = (from bib in Db.Items where bib.Id == item.Id select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
Db.ExecuteStoreCommand("update Bibs set Status= 'D' where Id={0}", item.BibId);
Db.SaveChanges();
}
}
}
return Json("S", JsonRequestBehavior.AllowGet);
}
function Test() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
//var bibjson = JSON.stringify(items1); **** Loose this line ****
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ "id": items1, "DelBib": cond }), // **** Items are stringified before posting ****
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});enter code here
}
else {
e.preventDefault();
}

Adding new row to SlickGrid

I have a slickgrid using the dataview. From what I can tell, the grid's add new row event isn't called until after the first new row field's editor is complete. The field I was editing is a custom editor that uses a input box with autocomplete and save the selected item "value" to the grid source data. The problem is the new "item" source isn't created until the grid add new row event is fired. I know there is a way around this and just want to know what is the best way to solve for this.
Thanks.
//Add new row event
grid.onAddNewRow.subscribe(function (e, args) {
var item = args.item;
addnewid = addnewid - 1;
item.inventorytransferdetailid = addnewid;
$.extend(item, args.item);
dataView.addItem(item);
});
// Custom editor
function Suggest2(args) {
var $input;
var defaultValue;
var scope = this;
this.init = function () {
$input = $("<INPUT type=text class='editor-text' />")
$input.width = args.column.width;
$input.appendTo(args.container);
$input.focus();
$input.bind("keydown.nav", function (e) {
if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
e.stopImmediatePropagation();
}
else if ($input.val().length > 0) {
$.ajax({
type: "GET",
url: "http://localhost:11111/GetProducts/" + $input.val(),
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$input.autocomplete({
source: data,
select: function (event, ui) {
var v = ui.item.value;
var l = ui.item.label;
//Set "display" field with label
args.item[args.column.field] = l;
this.value = l;
//Set "hidden" id field with value
args.item["productid"] = v;
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
})
};
this.destroy = function () {
$input.remove();
};
this.focus = function () {
$input.focus();
};
this.getValue = function () {
return $input.val();
};
this.setValue = function (val) {
$input.val(val);
};
this.loadValue = function (item) {
defaultValue = item[args.column.field] || "";
$input.val(defaultValue);
$input[0].defaultValue = defaultValue;
$input.select();
};
this.serializeValue = function () {
return $input.val();
};
this.applyValue = function (item, state) {
//item[args.column.field] = state;
};
this.isValueChanged = function () {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
};
this.validate = function () {
if (args.column.validator) {
var validationResults = args.column.validator($input.val());
if (!validationResults.valid) {
return validationResults;
}
}
return {
valid: true,
msg: null
};
};
this.init();
}
You can try below code.
function add_new_row(){
item = {
"id": (Math.round(Math.random()*-10000))
};
data_view.insertItem(0, item);
}
Then, bind with button.
<button onclick="add_new_row()">Add Row</button>

object parameters in Javascript

I'm having a bit of an issue with my javascript object. What I want to do is pass in an id and have it set a variable that is accessible to all of my functions.
Here's a small sample of what I have:
var myObject = function() {
var pageSize = 6;
var currentPage = 1;
var pagerPagesVisible = 5;
var pagerId = '#my-pager';
var entityId = '';
var doStuff = function() {
var endIndex = pageSize * currentPage;
var startIndex = endIndex - pageSize;
$.ajax({ type: "GET", url: "/items/" + this.entityId + "/entities/" + startIndex + "/" + pageSize + "/", dataType: "json", success: loadData, cache: false,
error: function(response, status, error) {
alert(response.responseText);
}
});
};
var loadData = function(data) {
var itemCount = data.length;
//build the html and write to the page
buildPager(itemCount);
};
var buildPager = function(itemCount) {
pager.build(pagerId, pageSize, itemCount, currentPage);
};
var attachEvents = function() {
//attach events to the pager
};
return {
init: function(entityId) {
this.entityId = entityId;
doStuff();
}
}
} ();
the issue is, in init, it sets the entityId instance that you see at the top. But when it hits doStuff() entityId is set back to ''.
You're mixing closure and object styles - you need to be consistent:
<script>
var myObject = function() {
var pageSize = 6;
var currentPage = 1;
var pagerPagesVisible = 5;
var pagerId = '#my-pager';
var entityId = '';
var doStuff = function() {
alert(entityId);
};
return {
init: function(myEntityId) {
entityId = myEntityId;
doStuff();
}
}
} ();
myObject.init(123);
</script>
Others have answered your question here, but I wanted to point out that you may want to use the prototype if you are going to be creating many of these objects.
When you enclose your methods you waste memory on every instantiation.
ClassName.prototype.methodname = function(){ ... }
That's because the entityId variable is local to the function and has nothing to do with the object you create at the end. Instead, put everything in that object at the end and not as locals in the function.
eg.
var myObject = function() {
var pageSize = 6;
var currentPage = 1;
var pagerPagesVisible = 5;
var pagerId = '#my-pager';
return {
doStuff: function() {
var endIndex = pageSize * currentPage;
var startIndex = endIndex - pageSize;
var self = this;
$.ajax( {
type: "GET",
url: "/items/" + this.entityId + "/entities/" + startIndex + "/" + pageSize,
dataType: "json",
success: function() { self.loadData(); },
cache: false,
error: function(response, status, error) {
alert(response.responseText);
}
} );
},
loadData: function(data) {
var itemCount = data.length;
this.buildPager(itemCount);
},
buildPager = function(itemCount) {
pager.build(pagerId, pageSize, itemCount, currentPage);
},
attachEvents: function() {
//attach events to the pager
},
entityId: '',
init: function(entityId) {
this.entityId = entityId;
this.doStuff();
}
};
}();

Resources