I am getting some string data along with files & i can access file like this Request.Files[0] but question is how can i access value of string objects? I am already trying to access it like this: Request.Form["url"] but seems not returns appropriate data. Please tell me how can i access Request.Form["url"] in a proper way.
Jquery Payload:
//FormData
var formData = new FormData();
$(".wholeBar").each(function (key, value) {
var findFiles = $(this).find(".hpicFile"); //find the element
var file = findFiles[0].files[0]; //get the actual file object
formData.append('files[]', file); //append all files to formData
// console.log(value);
var urlInput = $(this).find(".hurl");
formData.set("url", urlInput);
console.log(urlInput.val());
});
//Ajax request
$.ajax({
url: "/Controller/Upload",
type: "POST",
processData: false,
contentType: false,
data: formData, //Send form Data
success: function (response) {
console.log(response)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
C#:
var ddd = Request.Files[0];
var fff = Request.Form["url"];
//foreach (var item in fff)
//{
// var aaa = item.ToString();
//}
return Json("ok");
You can set string Data in below format in Jquery
var formData = new FormData();
var obj = {
Username: "user5",
Email: "em#example.com"
};
formData.set("data", obj);
and Receive it on Controller side as below format
VB.Net
Dim objUser As cls_User = JsonConvert.DeserializeObject(Of cls_User )(Request("obj"))
C#
cls_User objUser = JsonConvert.DeserializeObject<cls_User>(Request("obj"));
You need to create a class to capture the data coming from FormData() and then use the same object to retrieve it from (Request("obj") to Dim objUser As cls_User
Related
I know this has been asked a lot of times. But believe me I have tried them and this ain't working.
I have this simple List and Method :-
$scope.TblData = [];
var Name='Name'; var Desc='Desc';
$scope.TblData = [
{ Key: Name, Value: ClassSubjectName },
{ Key: Desc, Value: ClassSubjectDesc }
];
InsertFactory.InsertClassSubject($scope.TblData).then(function (d) {
alert(d.data + ' Subject Details');
}, function (error) {
alert('Cannot Save Contact Details');
})
Which I'm getting at factory like :-
BoardObj.InsertClassSubject = function (TblData) {
var ViewID = 'ClassSubject';
var Data = $.param({ TblList: ViewID, TblData: TblData });
return $http({
method: 'POST',
url: '/Admin/InsertTblData',
data: JSON.stringify(Data),
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
}
});
}
Trying to get it at server like this:-
if (Request.Form["TblData"] != null)
{
JsonData = Request.Form["TblData"].ToString();
}
aBundleInsert.TblDataParams = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(JsonData);
Ofcourse I'm doing it wrong but can't find the issue.
You are not posting your data as form post.
TblData is a scope variable, it will not come inside your Form object, Form is meant for input elements only.
Ideally you should be posting the data to a model at the server side, but if you still want to access it on server side, you can try like following.
string postContent = "";
HttpContext.Current.Request.InputStream.Position = 0;
using (var reader = new StreamReader(Request.InputStream,
System.Text.Encoding.UTF8, true, 4096, true))
{
if (HttpContext.Current.Request.ContentLength > 0)
{
postContent = reader.ReadToEnd();
}
}
I'm trying to export some data in my page sending a JSON object to my controller, calling this method:
[HttpPost]
public HttpResponseMessage Export([FromBody]List<PivotGridModel> lstPivotGrid)
{
transporte = GetList();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content = new ByteArrayContent(_Service.Export(transporte.Lista, lstPivotGrid));
response.Content.Headers.ContentType = mediaType;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = String.Format("Plan_{0:yyyy-MM-dd__HH-mm-ss}.xlsx", DateTime.Now);
return response;
}
The AJAX called when I click in the button 'Export' in my page is this one:
// the 'url' is the path of my controller and the 'data' is my object
executePostAjaxDataHeaders: function (url, data, headers) {
var obj = null;
utils.vars.callerName = arguments.callee != null && arguments.callee.caller != null ? arguments.callee.caller.name : "";
$.ajax({
type: "POST",
url: url,
async: false,
data: JSON.stringify(data),
headers: headers,
contentType: 'application/json; charset=utf-8',
beforeSend: function () { dxLoadPanel.funcs.show(); },
complete: function () { dxLoadPanel.funcs.hide(); },
success: function (data) { obj = data; },
error: function (request, status, error) { console.log(request); console.log(error); obj = utils.funcs.loadAjaxError(utils.vars.callerName, request, status, error); }
});
return obj;
}
When I click in the button on my page, the console returns me an error that says:
Error: Invalid XML: some random characteres like: �&N��>�
What am I missing? I wanted to download the file in my page... I was testing it using a 'Get' and calling my controller directly in the URL, but when I changed my method to a post (to get the data on my page) it stopped working.
I have issue with sending object contains array to a controller
this is my js code
var messageId = 0;
function DraftMessage()
{
var to = [];
var i = 0;
$('#to option:selected').each(function (index, element) {
to[i++] = $(element).val();
});
console.log(to);
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage", "Activities")",
datatype: "json",
traditional: true,
async: false,
data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
beforeSend: function () { }
}).done(function (Id) {
console.log(Id);
messageId = Id;
});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
and this is my controller side
public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
{
return new MessageActions().DraftMessage(draftMessage);
}
my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.
Can you change your request and use
dataType: "json",
contentType: "application/json;charset=utf-8",
This should work. Please let me know.
Try this. Push your object to array and send it as Json.
array.push({yourobject datas here})
$.ajax({
type: "POST",
url: '/DraftMessage/Activities',
contentType: 'application/json',
data: JSON.stringify(array),
success: function (d) {
..
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Convert your controller function's return type to JSonResult.
Hope helps.
do you want upload file using ajax ?!!
use the normal usage of form not the Ajax.BeginForm then in form submit event
write your code like this:
$('#Form').submit(function () {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = $('#Image').val();
if (file) {
var fname = $('#Image')[0].files[0].name;
if (CheckFile(file)) {
var uploadFile = document.getElementById('Image').files[0];
var myArray = [];
myArray.push(uploadFile);
if (myArray.length > 0) {
for (var i = 0; i < myArray.length; i = i + 1) {
fd.append("File1", myArray[i]);
}
}
}
else {
return false;
}
}
fd.append("ID", messageId);
fd.append("Title", $('#Title').val());
fd.append("Project", $('#Project').val());
fd.append("AreaId", $('#AreaId').val());
fd.append("Body", $('#messageBody').val());
var form = $('#Form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
fd.append("__RequestVerificationToken", token);
xhr.open("POST", "/ControllerName/Action/", true);
xhr.send(fd);
xhr.addEventListener("load", function (event) {
if (event.target.response != "OK") {
OnFail(event.target.response);
}
else {
OnSuccess(event);
}
}, false);
return false;
})
server side in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionName(Model pModel){
HttpPostedFileBase File = Request.Files["File1"];
if (File != null && File.ContentLength != 0){
//do what you want
return Content("OK");
}
else{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Error Messages", System.Net.Mime.MediaTypeNames.Text.Plain);
}
}
You can try a different approach. You can serialize your entire form by doing something like this:
var formdata = $("#frmEmailInfo").serialize();
and then post it to the Controller:
$.ajax(
{
type: "POST",
data: formdata,
dataType: 'json',...
I have a model I am trying to pass in from my view to my controller via an Ajax call which stringifies both the model and another string of data like this:
SetBinConfig: function (model, range) {
var _model = JSON.stringify(model);
var rangeSplit = range.split(/[ -]+/);
var _rangeSplit = JSON.stringify(rangeSplit);
var data = "model=" +_model + "&rangeSplit=" + _rangeSplit;
$.ajax({
url: '/IdentifiConfig/DefaultConfiguration/SetBinConfiguration',
type: 'POST',
data: "{'data' : '" + data + "'}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
if (data.error == 1) {
cc.jqUtils.openDialog(data.ErrorDescription, 'Error', 'OK', null, null, null);
}
},
error: function (x, h, r) {
console.log(x, h, r);
}
});
},
Which is then received by this method:
public ActionResult SetBinConfiguration(string data)
{
string range = data.Split(new string[] { "&rangeSplit=" }, StringSplitOptions.RemoveEmptyEntries)[1];
string tempModelData = data.Split(new string[] {"&rangeSplit="}, StringSplitOptions.RemoveEmptyEntries)[0];
string modelData = tempModelData.Replace("model=", "");
DefaultConfigurationModel model = new JavaScriptSerializer().Deserialize<DefaultConfigurationModel>(modelData);
string[] rangeSplit = Regex.Split(range, " - ");
foreach (IdentifiBINConfiguration ibc in model.IdentifiBINConfigs)
{
if (ibc.LowerRange == rangeSplit[0] && ibc.UpperRange == rangeSplit[1])
{
model.IdentifiBINConfiguration = ibc;
return Json(new { error = 0 });
}
}
return Json(new { error = 1 });
}
However, I get this error:
The value "System.Collections.Generic.Dictionary`2[System.String,System.Object]" is not of type "IdentifiMessenger.Implementations.Identifi.Object.IdentifiBINConfiguration" and cannot be used in this generic collection. Parameter name: value
And I don't know what that means at all. I know what the Dictionary is, but why can I not just deserialize this object? I followed other answers right here on SO and I don't understand why this isn't working.
Edit:
Model is quite literally my model, sent from my JS like this:
IdentifiConfig.SetBinConfig(#Html.Raw(Json.Encode(Model)), $('#BinRangesHidden').val());
And range is just a value from a hidden. I'm not posting back my model because I just need to modify one value and then have the page pull that modified value down later.
You still have to serialize your data.
data: JSON.stringify(data),
Then in your controller, your object should auto-parse:
public ActionResult SetBinConfiguration(MyData data)
Alternatively, you can parse it manually:
public ActionResult SetBinConfiguration(string data)
{
MyData resumeDto = JsonConvert.DeserializeObject<MyData>(data);
...
I am having problem while passing json data to the source of autocomplete multiselect jquery
this is the jason data which i am sending
[ "abhinav#sdv.com","nishimura#dscs.com","alex#sds.com","alice#sdvs.com","amit#sds.com"]
autocomplete: {
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/CommanService.asmx/ExtractEmail",
data: {},
dataType: "json",
success: function (data) {
var vServiceData = eval(data);
// alert(data.d[0].data123);
//return eval('[' + data.d + ']');
//response(vServiceData);
// alert(data);
response(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
})
}
in this source of ajax but the problem here is that istead of getting these record in
diffrent string the output is in the form of single string but when i pass static data like
source=["Red","blue","green"]
MY webservice code is
#region(EXTRACT EMAIL)
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string ExtractEmail()
{
//Webservice is used to extract the employee data
VisualLibrarySoapClient oVisualLibrary = new VisualLibrarySoapClient();
string data = oVisualLibrary.EmployeeSelectData();
DataSet ds = new DataSet();
ds = GetDataSet(data);
//Used data columns to extract email from data set
DataColumn ColEmail = ds.Tables[0].Columns["Email"];
//all emails are stored in a linst Mail
List<string> Mail = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
String MailData = row[ColEmail].ToString();
Mail.Add(MailData);
}
//Json serializer is used to convert the list data into jason format
//System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
// string a = JsonConvert.SerializeObject(Mail);
string ss = JsonConvert.SerializeObject(Mail, Formatting.Indented);
string d = ss.Substring(1, ss.Length - 1).ToString();
return ss;
//System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//return serializer.Serialize(Mail);
}
#endregion
directly in the source then the output is right i am getting this three words diffrently in autocomplete textbox suggestions plzz help thanx in advance