How to collect JSON in c# posted from angularjs? - c#

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

Related

Why querystring after ajax call while using datatable checkboxes?

I am trying to save the data by selecting multi checkboxes in datatables. But after ajax call in the submit click the the ajax not hitting success function. It is showing querystring along with the controller/action.Like following
https://localhost:44307/Leaves/Approval?leaveApproveDataTable_length=10&id%5B%5D=11
This is my js
$(document).on('click', '.btn-Approve', function (e) {
var form = this;
var rows = $(table.rows({
selected: true
}).$('input[type="checkbox"]').map(function () {
return $(this).prop("checked") ? $(this).closest('tr').attr('leaveid') : null;
}));
rows_selected = [];
$.each(rows, function (index, rowId) {
console.log(rowId)
// Create a hidden element
rows_selected.push(rowId);
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
var remarks = $('#Remarks').val();
console.log($(this).closest('tr').attr('leaveid'));
$.ajax({
url: '/Leaves/LeaveApproval',
data: { approveId: rows_selected, remarks: remarks },
type: 'POST',
processData: true,
dataType: 'JSON',
success: function (result) {
console.log(result);
debugger;
if (result) {
window.location.href = "/Leaves/Approval";
}
else {
return result;
}
},
error: function () {
}
});
});
This is my controller
public async Task<IActionResult> LeaveApproval(List<int> approveId, string remarks)
{
foreach (int id in approveId)
{
var leave = await _context.Leaves.FindAsync(id);
if (leave == null)
{
return Json(new { success = false });
}
leave.Status = "Approved";
leave.Remarks = remarks;
leave.ApprovedDate = DateTime.Now;
_context.Update(leave);
await _context.SaveChangesAsync();
}
return Json(new { success = true });
}
Kindly help me to solve the issue.
While returning from the controller replace:
return Json(new { success = true }); this line with
return Json(new { success = true }, JsonRequestBehavior.AllowGet);

jQuery AJAX Not Calling A C# Function In ASP.NET MVC

Basically, I am trying to call controller from views using jQuery ajax but it's not calling controller.
What I have to do is passing my token value from registration page to controller so that I will use its value for user registration.
< script type = "text/javascript" >
document.getElementById('LoginWithAmazon').onclick = function() {
options = {
scope: 'profile'
};
amazon.Login.authorize(options,
function(response) {
if (response.error) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token) {
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: {
token: 'abc'
},
cache: false,
success: function(result) {
alert(result);
}
});
}
function receiveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].Data);
}
}
}
return false;
};
< /script>/
Here below is my controller code
public JsonResult ProfileInfo(string token) {
return Json("test", JsonRequestBehavior.AllowGet);
}
I need to pass the token value from registration page to my controller
Try to change this in the controller
return Json("test", JsonRequestBehavior.AllowGet);
into
enter code herereturn Json(new { value="test" }, JsonRequestBehavior.AllowGet);
and change your js to be like this
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: JSON.stringify({
token: 'abc'
}),
cache: false,
success: function(result) {
alert(result);
}
});
Finally, i have solved the problem.I am unable to call the account controller so i have used my home controller for this purpose.Here below is the code that i have used for calling controller :
<script type="text/javascript">
document.getElementById('LoginWithAmazon').onclick = function() {
options = { scope : 'profile' };
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token)
{
var url = "/home/ProfileInfo?token=" + token;
var request = $.ajax({
url: url,
method: "GET",
dataType: "json"
});
request.done(function (msg) {
var data = [];
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
});
}
}
</script>

MVC Redirecting Action using Json

Purpose: The code written is suppose to save all the contents using Json and re direct to action.
Problem:
The current redirect using Json does not allow the redirection as suppose.
return new JsonResult { Data = new { status = status } };
The code is below for reference: Looking for suggestions:
View Code
$.ajax({
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
window.location.href = d.Url;
//clear form
t = [];
d = [];
r = [];
$('#SN').val('');
$('#SA').val('');
$('#t').empty();
$('#d').empty();
$('#r').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
});
Controller
public JsonResult Save(SAVM O,)
{
bool status = false;
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
SA s = new SA
{
}
_db.SA.Add(O)
_db.SaveChanges();
status = true;
}
else
{
status = false
}
return new JsonResult { Data = new { status = status } };
}
Here want to redirect like this:
return RedirectToAction("F", "SA");
but using JsonResult
Solution
View
$.ajax({
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
window.location.href = d.Url;
})
} });
Controller
public JsonResult Save(SAVM O,)
{
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
SA s = new SA
{
}
_db.SA.Add(O)
_db.SaveChanges();
return Json(new { Url = "F/SA" });
}
You have a couple of options here, you decide which one you prefer based on your requirements.
Do not use AJAX. AJAX requests are meant for data required for the current page. You should use a synchronous request for the redirection.
Return the URL to which the client should redirect on the success event:
return Json(new { url = "/F/SA" });
And then:
success: function (d)
{
window.location.url = d.url;
}
Return the already rendered View and load it to the current page:
return View("some view...");
And then:
success: function (d)
{
$("#someElement").html(d);
}

Passing custom success/error messages to ajax call from asp.net controller

Im working with ASP.Net Core and I'm trying to have everything localized. I have no isses localizing strings from the controller or right in the view but I do have an ajax call from javascript that currently has hard coded english success/error messages. My initial thought is I could just pass the localized success/error message back to the ajax call from the controller. I'm thinking this will be easy enough with the ajax success function but Im not really sure how to pass an error message to the error/fail function.
Here is my ajax call:
$.ajax({
type: "POST",
url: '#Url.Action("SaveGridState", "Account", new { gridID = 3 })',
data: {
options: JSON.stringify(gridState)
},
async: true,
success: function(data) {
var staticNotification = $("#staticNotification").data("kendoNotification");
staticNotification.show({
message: "Grid State Saved"
}, "success");
var container = $(staticNotification.options.appendTo);
container.scrollTop(container[0].scrollHeight);
},
fail: function() {
var staticNotification = $("#staticNotification").data("kendoNotification");
staticNotification.show({
message: "Grid State Save Failed"
}, "error");
var container = $(staticNotification.options.appendTo);
container.scrollTop(container[0].scrollHeight);
}
});
Here is my function from my controller:
public bool SaveGridState(string options, int gridID)
{
try
{
UserStore ustore = new UserStore(_settings);
HttpContext.Session.LoadAsync();
uint user_id = (uint)HttpContext.Session.GetInt32("UserID");
options = options.Replace("'", #"\'");
return ustore.SaveGridState(user_id, gridID, options);
}
catch(Exception ex)
{
return false;
}
}
Is there a way to define my success/error message from the SaveGridState function and pass it to the ajax function?
I ended up taking the advice of #MarkG and #AndreasHassing and changed my function to return an IActionResult and then used Ok() and BadRequest().
Here is what my controller function looks like now:
public IActionResult SaveGridState(string options, int gridID)
{
try
{
UserStore ustore = new UserStore(_settings);
HttpContext.Session.LoadAsync();
uint user_id = (uint)HttpContext.Session.GetInt32("UserID");
options = options.Replace("'", #"\'");
bool success = ustore.SaveGridState(user_id, gridID, options);
return Ok(new { Result = success, Message = success ? _localizer["GridSaveSuccess"].Value : _localizer["GridSaveFail"].Value });
}
catch (Exception ex)
{
return BadRequest(new { Result = false, Message = _localizer["GridSaveFail"].Value });
}
}
And my ajax call looks like this:
$.ajax({
type: "POST",
url: '#Url.Action("SaveGridState", "Account", new { gridID = 3 })',
data: { options: JSON.stringify(gridState) },
async: true,
success: function (data) {
var staticNotification = $("#staticNotification").data("kendoNotification");
if (data.Result) {
staticNotification.show({
message: data.Message
}, "success");
}
else {
staticNotification.show({
message: data.Message
}, "error");
}
var container = $(staticNotification.options.appendTo);
container.scrollTop(container[0].scrollHeight);
},
error: function (data) {
var staticNotification = $("#staticNotification").data("kendoNotification");
staticNotification.show({
message: data.Message
}, "error");
var container = $(staticNotification.options.appendTo);
container.scrollTop(container[0].scrollHeight);
}
});

Sending object to a controller in asp.net mvc using ajax

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',...

Categories