My project is Asp.net MVC Core.
I try to upload a file with angularjs to mvc controller but i make some mistakes; sending value is null in method. I can write a console log , actually data is not null but problem is sending to the controller.
angular.module("myApp").controller("myVm", function ($scope, $http, $window) {
var vm = $scope;
var url = "UploadSingle";
var config = {
headers: {
"Content-Type": undefined,
}
};
vm.upload = function () {
var formData = new $window.FormData();
formData.append("file-0", vm.files[0]);
console.dir(formData);
$http.post(url, formData, {
transformRequest: angular.identity,
headers: new HttpHeaders().set('enctype', 'multipart/form-data')
}).
then(function (response) {
vm.result = "SUCCESS";
vm.data = response.data.data;
}).catch(function (response) {
vm.result = "ERROR " + response.status;
});
};
public async Task<JsonResult> UploadSingle(IFormFile formData)
{
using (var reader = new StreamReader(formData.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(formData.ContentDisposition);
var fileName = parsedContentDisposition.FileName;
}
return Json(new { result = "Test" });
}
Related
I am using google recaptcha v2 in my application I'd integrate it in client side.
Here is my code
<script>
var onloadCallback = function () {
grecaptcha.render('recaptcha', {
'sitekey': '6Lc_qmcUAAAAAJW_kALWjxcxcvxcxcvxcvxc',
'callback': reCaptchaCallback,
});
};
var reCaptchaCallback = function (response) {
if (response !== '') {
console.log(response);
}
};
function getReCaptchaRes() {
var message = 'Please check the checkbox';
if (typeof (grecaptcha) != 'undefined') {
var response = grecaptcha.getResponse();
(response.length === 0) ? (message = 'Captcha verification failed') : (message = '');
}
$('#reCaptchaLblMsg').html(message).css('color', "red");
return !(response.length === 0)
}
submitHandler: function (form) {
// call the google recaptcha validation
if (getReCaptchaRes()) {
$('.spinner-holder').css('display', 'block');
$("#myAjaxRegisterModal2 input[type='submit']").val("Saving ...").attr('disabled', 'disabled');
var __RequestVerificationToken = $('[name="__RequestVerificationToken"]').val();
var RegisterData = {
__RequestVerificationToken: __RequestVerificationToken,
ProfileCreatedFor: $('#ddlProfileCreatedFor').val(),
GroomBrideName: $('#txtName').val(),
Mobile: $('#txtMobile').val(),
EmailID: $('#txtEmail').val(),
Height: $('#ddlHeight').val(),
Gender: $("input[name='Gender']:checked").val(),
MaritalStatus: $('#ddlMaritalStatus').val(),
DOBMonth: $('#ddlMonth').val(),
DOBDate: $('#ddlDate').val(),
DOBYear: $('#ddlYear').val(),
State: $('#ddlUserState').val(),
City: $('#ddlCity').val(),
Section: $('#ddlUserSection').val(),
DivisonText: $('#DivisonText').val(),
Password: $('#ConfirmPassword').val()
}
//form.submit();
$.ajax({
url: "/Home/RegisterNewMemberByJson",
type: "POST",
data: RegisterData,
dataType: 'json',
success: function (data) {
if (data == "Error") {
window.location.href = "/Home/Index";
}
else if (data == true) {
$('#myAjaxRegisterModal2').modal('hide');
RegisterPopUp();
}
else {
$('.spinner-holder').hide();
$("#myAjaxRegisterModal2 input[type='submit']").val("Save").removeAttr("disabled");
$('#ageErrorMsg').text(data);
}
}
});
}
}
<div class="clearfix"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
</script>
But my concern is if I will change response from browser console then I can hit the ajax method multiple times using a loop. So how can I prevent it to hit my ajax method into loop Or there is something wrong with my captcha integration.
My another concern is is it possible to check the captcha response on the client side as well as on the server side. if possible then how.
Please help me any kind of help will be appreciated.
Now I can answer my own question. I was making a stupid mistake I was not sending the response through ajax and was trying to get the response into my method on controller through [g-recaptcha-response].
Here is the updated code.
public JsonResult RegisterNewMemberByJson(ReligionAndEthinicityModel RegisterData)
{
if (ModelState.IsValid)
{
try
{
bool captchaIsvalid = IsReCaptchValid(RegisterData.cResponse);
if (captchaIsvalid)
{
public bool IsReCaptchValid(string cResponse)
{
var result = false;
var captchaResponse = cResponse;
var secretKey = Convert.ToString(ConfigurationManager.AppSettings["RecaptchaKey"]);
var apiUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";
var requestUri = string.Format(apiUrl, secretKey, captchaResponse);
var request = (HttpWebRequest)WebRequest.Create(requestUri);
using (WebResponse response = request.GetResponse())
{
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
JObject jResponse = JObject.Parse(stream.ReadToEnd());
var isSuccess = jResponse.Value<bool>("success");
result = (isSuccess) ? true : false;
}
}
return result;
}
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 trying export file with web Api.
this is my client code :
exportLicense(licenseIds) {
return this.$http({
method: 'POST',
contentType: "application/zip",
url: this.application.resolveWebApiService('Licenses', 'ExportLicenses'),
data: licenseIds
});
}
ExportLicenses method from my backend side(mycontroller.cs) function and as the following :
[HttpPost]
[Route("ExportLicenses")]
public async Task<IHttpActionResult> ExportLicenses([FromBody] int[] licenseIds)
{
Contract.Requires(ModelState != null);
if (!ModelState.IsValid)
{
return CustomReturnMessage(CustomHttpStatusCode.UnprocessableEntity, "Bad request", Request, ResponseMessage);
}
var task = exportLicensesTaskFactory(licenseIds);
var taskResult = await task.TryRunAsync();
if (!taskResult.Item1 || taskResult.Item2 == null)
{
return CustomReturnMessage(422, $"Failed to import license file:\n{task.Exception}", Request, ResponseMessage);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new ByteArrayContent(taskResult.Item2); //taskResult.Item2 is a byte[]
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return ResponseMessage(response);
//return Content(HttpStatusCode.OK, taskResult.Item2);
}
I do not need to do any file/zip operations because my task already does this and it returns a byte [] to me.(taskResult.Item2)
my return response from my service like this :(like a corrupted string)
res.data
"PK- Њ"LH,����������4 ORDER_AVEA_0001_10042_PMEXCH003_20175211_License.xml . �UY��F}���0�W+�b`4w"�}��%b���ί�57�w�EQ�~�:�T�]�s>~]��eJa�5��W�������O�4F���*5e�'��ߗ>�����A�y~���E�?�*|����7������gۗ�>��ɧ������o����b�i[6k���3���b�4K�]'RÚ���˥��D�ٝ)J!g�������
�a�7+bx��w�6���q�+�L�}�G�̐2�4�$GZk�;hg[�t$�s�۵s��m���&I?-]8 E��+�B�,N�>��!��
`o
��~'�w�| ?�*�����}.<0�E߿���� �<�N����
����:�1}}A�Fh�z��a�
�����,#Q�k�?o����)u����l�e���g��Y�^��Ľ�\�tF�mK�-�lH2�MҞ)�m�s�r�*�����~��,���o���/��XD�Au�y6/�tS-Q�V��rA��_jg����7{��x,�{�虜��w���*D{�Ǖ0��u��*.奟��#<�ܑ��k�H�k"oi=����]�2��2�5���<v2_f=e)z�K4Ͽ(7O�ET�)x���^���Q�X���!R�䰯
-&S]v��������fl: ��9��V{sf�)�:Ĉ\e�Cjm�e��G[��z%��z�<wNƅ�M�'�a>��v�zR-ɛ���鱍T7(�37�r[�ɻ&��ڻ�E�L�ie�زO�da��쵸Q�� 18#r��N[�Y�?�]j�0�Mk0^�ۏ؍?Fg^�.Xp|n�e��`����N:&M �Z+��o��6��~�
�wـw��4�� ��n�$��.��[)��Bb��8![*�L|���&Jf�Tc�u#?Ƃ���1�o��B�XW�[hFr.�]��y��+^���������U�d�T��9�]{��K���ẍ́���!Y������7�<Ώ���-F_��:u�f����Iasr~F�u�9�`�M�O���
�m�p��a���1T�&����y%3*��]H[G �r�]u�nk^+'�y�#���8��T�x-G*p�\(}q��8.�b^�Aٟz�^�.��<��SO$d�tT"�r)8Щ�wB�;NB����<S-�[�EBVǽ�č�I��-�z-��0���k7y~J��/\g ti�������z"x9L#P�_���S�ة6�z�T�X�N��_h�l�'��k�)I>]��W7�`fK�#~�/q�:���#���}�Ow�G��������PK3 - Њ"LH,����������4 ORDER_AVEA_0001_10042_PMEXCH003_20175211_License.xml . PK v � "
We can use something like this :
postdownload: function (url, fileName, data) {
authenticationService.getAuthenticationToken().then(function (token) {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", url);
$('<input>').attr({ name: 'authToken', type: 'hidden' }).val('Bearer ' + token).appendTo(form);
$('<input>').attr({ name: 'fileName', type: 'hidden' }).val(fileName).appendTo(form);
$('<input>').attr({ name: 'data', type: 'hidden' }).val(data).appendTo(form);
document.body.appendChild(form);
form.submit();
$('form > input[name=authToken]').val('');
$('form > input[name=fileName]').val('');
$('form > input[name=data]').val('');
}, function (reason) {
return $q.reject({
config: config,
headers: {},
status: 0,
data: null
});
});
}
and we should be call like this :
var serialized = JSON.stringify(licenseIds);
var url = this.application.resolveWebApiService('Licenses', 'ExportLicenses?' + idsString + '');
this.uiHelper.postdownload(url, "asd.zip", serialized);
and edited my backend side code like this :
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new ByteArrayContent(taskResult.Item2);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return ResponseMessage(response);
I'm a basic developer, I just need to collect the following JSON data in a c# file:
{
"text":"This is a message !!!",
"userid":"some_id",
"username":"username",
"fname":"some_name",
"lname":"some_surname",
"iurl":"url_here",
"type":"some_type"
}
The above array is posted using angularjs.
app.js:
var app = angular.module('myApp');
app.controller('WorkingCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.form = {};
$scope.post = [];
$scope.submitForm = function () {
$scope.post.text = $scope.form.text;
if ($scope.post.text != '') {
$scope.post.unshift($scope.post.text);
$scope.post.text = '';
}
$scope.remItem = function ($index) {
$scope.post.splice($index , -1);
}
$scope.form.userid = "some_id";
$scope.form.username = "username";
$scope.form.fname = "some_name";
$scope.form.lname = "some_surname";
$scope.form.iurl = "url_here";
$scope.form.type = "some_type";
$scope.showValues = JSON.stringify($scope.form);
}
}]);
As clearly seen above showValues returns the array.
Now I just wanted to collect data in my ValuesController.cs file. Can anyone suggest how to do that ?
You could also try this code:
Create a service.
app.service("angularService", function ($http) {
this.AddValues= function (showValues) {
var response = $http({
method: "post",
url: "api/values/YourmethodName",
data: showValues
});
return response;
}
});
In your controller: Inject your Service here in this way to implement its method/service
app.controller('WorkingCtrl', ['$scope','angularService',function ($scope, angularService) {
$scope.submitForm = function () {
$scope.form = {};
$scope.form.userid = "some_id";
$scope.form.username = "username";
$scope.form.fname = "some_name";
$scope.form.lname = "some_surname";
$scope.form.iurl = "url_here";
$scope.form.type = "some_type";
$scope.showValues = JSON.stringify($scope.form);
angularService.AddValues(showValues ).then(function (result) {
}
}]);
You should create a service which sends the data to your controller. You need something along these lines:
app.factory('WorkingService', ['$http', '$q', function ($http, $q) {
saveData: function (showValues ) {
var deferred = $q.defer();
$http.post(yourMVCUrl, showValues ).then(function (result) {
deferred.resolve(result);
});
return deferred.promise;
}
}
In your angular controller, just call the service WorkingService.saveData($scope.form).
You can make call to your MVC controller (ValuesController.cs) using this code in your Angular controller:
$http({
method: 'POST',
url: '/Values/TestMethod',
data: $scope.showValues,
headers: { 'content-type': 'application/json' }
}).
success(function (data) {
//do some operations with the return data if the MVC controller returns data
}).
error(function () {
alert("Error has happened..");
});
It is better to put the ajax request in a factory service and from your controller to call the http method from the service
I am trying to upload image, using ajax. i am sending request like this:
#using (Ajax.BeginForm("SaveReferral", "ReferralIM", new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccessReferralSent"
}, new { id = "frmReferral", onSubmit = "OnControlMapping(this);" }))
{
}
if i send request like this:
#using (Html.BeginForm("SaveReferral", "ReferralIM", FormMethod.Post, new { id = "frmReferral", enctype = "multipart/form-data" }))
{
File uploaded successfully, but i want to use ajax ,Please help me how i should do for file uploading with ajax.
Thanks
I am not using MVC BUT if you want to use $.ajax then here it is...
$('.file-uploadID').on('click', function (e) {
e.preventDefault();
var fileInput = $('.file-uploadID');
var fileData = fileInput.prop("files")[0]; // Getting the properties of file from file field
formData.append("file", fileData); // Appending parameter named file with properties of file_field to form_data
formData.append("user_email", email); //adding email address as parameter if you have
$.ajax({
url: '/FileUploadHandler.ashx',
data: formData,
processData: formData.processData,
contentType: formData.contentType,
type: 'POST',
success: function (data) {
var obj = $.parseJSON(data);
if (obj.StatusCode == "OK") {
alert("file upload done");
} else if (obj.StatusCode == "ERROR") {
alert("file upload error");
}
},
error: function (errorData) {
$('.result-message').html("There was a problem uploading the file. Please try again.").show();
}
});
});
Handler
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
var email = context.Request.Params["user_email"];
var fileData = context.Request.Files["file"];
try
{
var result = UploadImageToServer(email, fileData);
context.Response.Write(result);
}
catch (Exception ex)
{
context.Response.Write("error while uploading file to the server, please try again.");
}
}