Retrieving POSTED data from controller - angularjs

I'm using angular js. I posted data to a controller in vb.net from a JS file. How can I retrieve the data in the vb controller?.
Below is my app.factory method.
UpdateServiceData: function (p1, p2) {
var data = $.param({
fName: "John",
lName: "Smith"
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http({
method: "post",
url: '../api/Service/UpdateSvcData',
data,
config,
params: {
'P1': p1,
'P2': p2
}
}
});
}
UpdateSvcData is a method inside the controller ServiceController.vb
I just need to retrieve the posted values inside ServiceController.vb
i.e., I need to get fName and lName.
In short, I'm posting values from a JS file. I need to retrieve it at the ServiceController.vb using vb.net
I tried Request.QueryString("fName"), Request.Form["fName"] etc. But these are not giving the results.
Thanks
Public Function UpdateServiceData(<FromUri()> request As ServiceEntities) As HttpResponseMessage
Dim success As Boolean = True
Dim response As HttpResponseMessage
Try
Dim dataAccess As DB.DataAccessBase = DB.DataAccessBase.GetInstance(DataAcessTypes.Service)
request.MethodName = "UpdateServiceData"
Dim sJSON As String = dataAccess.Select(Of ServiceEntities)(request)
response = Me.Request.CreateResponse(HttpStatusCode.OK)
response.Content = New StringContent(sJSON, Encoding.UTF8, "application/json")
Catch ex As Exception
response = Me.Request.CreateResponse(HttpStatusCode.InternalServerError)
End Try
Return response
End Function

You need to return the $http object to the controller if I understand your question, hard to tell without seeing the controller though.

Related

Convert Json string to object List in angular controller MVC web application

Guys I'm stuck with something. I have to convert a Json string to an object list.
I am working on a MVC project and I'm in the middle of an API integration.
Here's the data of the problem. I managed to get data list(has a tree structure) object from a cloud api and converted it to a Json string in MY WEBAPI.
This is the query
var textvar = (from avbH in avb_Hotels
join catRs in cat_Rs on avbH.categoryCode equals catRs.code
join rep in hotelRepList on avbH.code equals rep.code
select new
{
code= avbH.code,
destinationCode = avbH.destinationCode,
description = rep.description,
hotelstar = catRs.simpleCode,
checkIn = hotelBooking.DepartureDate,
checkOut = hotelBooking.ReturnDate,
name = avbH.name,
address = rep.address,
accommodationTypeCode = rep.accommodationTypeCode,
minRate = (int)Math.Round(Convert.ToDecimal(avbH.minRate) * rates),
images = "http://photos.hotelbeds.com/giata/" + rep.imagepath,
rooms = avbH.rooms,
ratecomment = avbH.ratecomment,
});
This is the converting part and I returned it as a string to the webUI.
result = JsonConvert.SerializeObject(textvar2, Newtonsoft.Json.Formatting.None);// then returns result
I need to convert this again to a object tree in the angular controller of my webUI.
I tried angular.fromJson but it doesn't work
app.service("APIService", function($http) {
this.hotelavailability = function(sub) {
return $http({
method: "post",
data: sub,
contentType: "application/json; charset=utf-8;text/plain",
timeout:30000,
url: "/api/HotelBooking/Availability"
});
}
app.controller("APIController", function ($scope, $window, $http, filterFilter, APIService, States) {
var getAll = "";
getAll = APIService.hotelavailability(sub);
getAll.then(function (d) { // d has the returning Json string
console.log("Succss");
$scope.hotels = angular.fromJson(d.data); //deserialization<-- This doesnt work
console.log($scope.hotels);
$scope.respData = angular.fromJson(d.data);
}
This is d(returning Json string from the webAPI)
getAll.then(function (d) { // d has the returning Json string
console.log("Succss");
$scope.hotels = angular.fromJson(d.data);
$scope.hotellist = angular.fromJson($scope.hotels);
}
I think this will work.

In ASP.NET MVC, how to save image in SQL Server uisng ajax post method?

I have a database with a varbinary(max) column for storing an image. I'd like to save the image in the database using Ajax (with controller actions and Entity Framework). Further, I'd like to retrieve the saved image and display it on the view (but that's another problem).
After looking around, I saw this https://stackoverflow.com/a/25768212/7885071
From that answer I have the following Ajax function :
function SaveImageViaAjax() {
var id = 123;
var formData = new FormData();
var totalFiles = document.getElementById("imageUploadForm").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("imageUploadForm").files[i];
formData.append("imageUploadForm", file);
}
$.ajax({
type: "POST",
data: {
"id":id
"image": formData
},
url: '/MyController/MyAction/',
success: function (response){
// alert(success);
},
error: function (xhr, status, error) {
alert("error");
}
});
}
If that function is correct, my problem is I don't know how to use an Action to populate/read the database.
Using https://stackoverflow.com/a/25400976/7885071 , I have properly set my model with byte[] for the image but how to deal with the action?
Here is what I propose :
Action to save the image in database:
[HttpPost]
public string SaveImageFromAjax(int id, byte[] image) //same as Ajax data section...
{
using(var db = myDbContext())
{
var MyObject object1 = new MyObject();
object1.id = id;
obecjt1.photo = image;
db.MyObject.Add(object1);
db.SaveChanges();
}
return "my message";
}
I know I must be far from the right code. Hopefully you'll kindly guide me to it...

How to send a string value to a function (ng-click)

I've got a very simple questions;
Here's my HTML;
<button ng-click="projectTypeController.deleteProjectType(pt.Code)">X</button>
And my function in my controller:
self.deleteProjectType = function (projectTypeCode) {
$http.post('http://localhost:49165/Service1.svc/projecttypes/delete/', projectTypeCode)
.then(getProjectTypes)
.then(function (response) {
});
};
Code in my webservice:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "ProjectTypes/Delete/", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void DeleteProjectType(string projectTypeCode);
This works perfectly fine as long as 'pt.Code' is numeric, but as soon as it's a string it results in a HTTP 400 Bad Request. So I think i'm doing something wrong with the deleteProjectType(pt.Code) Part.
I tried to look for examples where they pass a string into a method, but i cannot find anything...
the pt.Code = a scope variable by the way, also adding data in the form of object inside a form element works fine, so passing strings in an object is not a problem, just passing a single string, instead of an integer to a method doesn't seem to work
You need to format the parameter as a valid json.
To do that you can use JSON.stringify().
To implementet this in the method
self.deleteProjectType = function (projectTypeCode) {
$http.post('http://localhost:49165/Service1.svc/projecttypes/delete/', JSON.stringify(projectTypeCode))
.then(getProjectTypes)
.then(function (response) {
});
};
I prefere to use objects instead of just sending a value as a string.
If you at any time need to extend the body then you only need to add more fields to the objects and not modify the function call or the service method.
Here's an example of how you could do that
self.deleteProjectType = function (projectTypeCode) {
var data = { code: projectTypeCode};
$http.post('http://localhost:49165/Service1.svc/projecttypes/delete/', JSON.stringify(data))
.then(getProjectTypes)
.then(function (response) {
});
};
Create the class server side
Public class ProjectTypeDTO
{
public string code { get; set; }
}
Add the class as the parameter in the service method and you are gtg
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "ProjectTypes/Delete/", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void DeleteProjectType(ProjectTypeDTO pt);

Json array is null when received in controller

function viewReports(firstDate, lastDate) {
var selected = $('#ReportSelected').find(":selected");
var controller = "PortalReports";
var method = "GetReport";
var urlAjax = $("#basePath").val() + controller + "/" + method;
var companydropdown = $('#ReportSelected :selected').data("companydropdown");
var agencydropdown = $('#ReportSelected :selected').data("agencydropdown");
var userdropdown = $('#ReportSelected :selected').data("userdropdown");
var data =
{
reportSelected: selected.text(),
firstDate: firstDate,
lastDate: lastDate,
companydropdown: companydropdown,
agencydropdown: agencydropdown,
userdropdown: userdropdown
};
/*var data =
[{
"reportSelected": selected.text(),
"firstDate": firstDate,
"lastDate": lastDate,
"companydropdown": companydropdown,
"agencydropdown": agencydropdown,
"userdropdown": userdropdown
}];*/
var answer = JSON.stringify({ data });
$.ajax({
traditional: true,
data: JSON.stringify({ data }),
url: urlAjax,
success: function (response) {
loadReport(response);
},
error: function (ob, errStr) {
alert("An error occured. Please try again.");
}
});
//Mvc
public JsonResult GetReport(JArray data)
{
var persons = data.Select(x => x.ToObject<InputJson>());
JArray data is always null irrespective of how many ways I add square brackets of remove quotation marks etc, what am I doing wrong!!!
Prefer simple Object returned in array for readability as I might need to add to it.
Since you are sending a complex data structure(array), you should specify the contentType property when making ajax call. Specify the value of contentType property as "application/json"
//Values hard coded, you may replace with real values from your form.
var dataArray = [{
reportSelected:'201501',
firstDate: '11/12/2010',
lastDate: '12/12/2010',
companydropdown: 4,
agencydropdown: 6,
userdropdown: 16,
}];
var urlAjax = "/Home/GetReport"; // Hard coded for demo. Read further..
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify(dataArray),
url: urlAjax,
success: function (response) {
console.log(response);
},
error: function (ob, errStr) {
alert("An error occured. Please try again.");
}
});
I suggest you create a view model /DTO to represent the data you are sending and use that in your action method.
public class ReportRequest
{
public string reportSelected { get; set; }
public DateTime firstDate { get; set; }
public int companydropdown { get; set; }
}
[HttpPost]
public JsonResult GetReport(IEnumerable<ReportRequest> data)
{
//do something with data
// to do : Return something
}
In the example, I hardcoded the value of urlAjax variable. You may consider using the html helper methods to generate the correct relative url path to the action method(s) as explained in this post.

Passing JSON array to MVC Controller Action not working

We want to pass a JSON array to an MVC Controller Action. The Action Takes a list of Cards as parameter. When we call the Action, the parameter is null.
This is the client-side code:
function PrintCards() {
var CardsArray = [];
CardsArray = GenerateArrayOfCards();
//CardsArray has the desired data
var errors = JsonResults('/Operator/PrintCards', 'Cards=' + CardsArray, 'Post');
if (errors != '') {
alert('Something went wrong!');
return false;
}
alert('Cards got Successfully assigned.');
}
And on the server-side we have the following Action
Public Function PrintCards(Cards As List(Of Card)) As JsonResult
Try
PrintAllCards(Cards)
Return Json(String.Empty, "application/json", UTF8Encoding.UTF8)
Catch ex As Exception
Return Json(New With {.error = "Something went wrong!"}, "application/json", UTF8Encoding.UTF8)
End Try
End Function
The problem is that in the Action, Cards is null while in the view (client-side) the array has data. Is there any convert or something missing?

Resources