Passing localstorage to controller using Ajax - javascript

I need to access the data held in localstorage, server side but that's another story.
I have this button in my view:
<div style="float:right;">
<input id="btnTest" type="button" name="test Json Button" value="test Json Button" onclick="sendLocalStorage();" class="btn btn-default" />
</div>
This JS function:
function sendLocalStorage() {
var JsonLocalStorageObj = JSON.stringify(localStorage);
//var test = ["test1", "test2", "test3"];
$.ajax({
url: "/MyControllersName/Test",
type: "POST",
dataType: 'json',
data: JsonLocalStorageObj,
contentType: "application/json; charset=utf-8",
beforeSend: function () { alert('sending') },
success: function (result) {
alert(result.Result);
localStorage.clear();
}
});
};
And this test controller method:
[HttpPost]
[WebMethod]
public ActionResult Test(string JsonLocalStorageObj)
{
string x = JsonLocalStorageObj;
//deserialize here
return RedirectToAction("Index");
}
When I run JSON.stringify(localStorage); in chrome dev tools, I see data as expected, however when I debug my controller JsonLocalStorageObj is always null. As a test I used the test array that is commented out and set the parameter on the controller to accept a List<string> and this came through populated.
Whats the problem with JSON.stringify(localStorage); being passed through?

You haven't specified the parameter name of your action (JsonLocalStorageObj) and your content and dataType were wrong too.
Try change your javascript code to this:
function sendLocalStorage() {
var JsonLocalStorageObj = JSON.stringify(localStorage);
//var test = ["test1", "test2", "test3"];
$.ajax({
url: "/MyControllersName/Test",
type: "POST",
data: { JsonLocalStorageObj: JsonLocalStorageObj },
success: function (result) {
alert(result);
}
});
}

Related

Js function passes null to the controller, in the old version

I need to wrote a code on an older version of the .net Framework, namely 4.5.2.
I ran into a problem, the ajax code sends an empty request to the controller.
Here is the form and I need to check user Full Name on unique:
<div class="register-card">
<h1>Register the new user</h1>
#using (Html.BeginForm("CreateUserAsync", "Home", FormMethod.Post))
{
<div>
#Html.Label("FullName", "Enter your full name")
<input type="text" id="FullName" name="FullName" pattern="^(\w\w+)\s(\w+)\s(\w+)$" onblur="CheckAvailability()" required />
<span id="message" onclick="ClearMessage()"></span>
</div>
<p><input type="submit" value="Send" id="submit" /></p>
}
</div>
Here is my js function to checking Full Name:
function CheckAvailability() {
var data = $("#FullName").val();
var param = data;
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "String",
data: JSON.stringify(param),
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
};
function ClearMessage() {
$("#message").html("");
};
Js function pass the FullName to next controller:
[HttpPost]
public async Task<JsonResult> CheckFullNameAsync([FromBody]string fullName)
{
var isValid = await _service.IsUserExistAsync(fullName);
return Json(isValid);
}
But the controller receives null.
I think the problem is in the Js function, but I can figure out what I'm doing wrong.
Dont need to create two variable
var data = $("#FullName").val();
var param = data;
Just create
var param = $("#FullName").val();
try this
Check this link. it explains your problem well
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: 'json',
data:{"":param},
//data: { fullName: param },
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
or this one also
$.post('/Home/CheckFullNameAsync', { fullname: param},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
What is dataType: "String"? That's not a listed option. And more specifically, all you're sending is a value but with no key. So the server isn't able to deserialize the data and determine where the fullName value comes from.
Change the type to 'json' and send the object with the named key for the value:
dataType: "json",
data: { fullName: param },

How to pass local storage item to MVC controller

I am trying to pass an array of strings from my local storage (key value) to MVC controller. Here's my code:
In cshtml View file:
<script>
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result.Result);
}
}});
}
</script>
<button onClick="getFavouriteBooks()">Display Favourites</button>
My controller:
public async Task < ViewResult > Favourites(string ids) {
// code that fetches book data from API
if (data != null)
{
var bookList = JsonConvert.DeserializeObject < Book[] > (data);
foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
}
return View("Index");
}
The controller action gets called successfully on the button click but the ids parameter is always null even though it isn't when in the console. Where am I going wrong?
from what you have described, I strongly feel this is the problem of expecting asynchronous function to behave synchronously,
await foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
Try adding await before you call foreach loop. or better use for in loop
Thanks for your help everyone, the solution was actually to change this part of the ajax call to:
data: { ids: localStorage.getItem('videoIds') },
This code was tested in Visual Studio.
You have to create a viewModel:
public class IdsViewModel
{
public string[] Ids { get; set; }
}
Replace this:
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
// or you can use
var ids = localStorage.getItem('videoIds'); //it still will be working
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
with this
var ids= JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '/Home/Favourites',
data: { ids:ids },
success: function (result) {
....
and the action
public async Task <ActionResult> Favourites(IdsViewModel viewModel) {
var ids=viewModel.Ids;
.....

Posting request from javascript in AJAX to C# methods, no returning value, ASP.NET, MVC

Environment:
<package id="jQuery" version="3.2.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />
I tried to post a request from one of my javascript files to my methods in C# file. So far the request returns 200 OK, but the response content is empty, using console.log(response) it shows undefined. Is it the problem with my requesting url or I didn't make my C# function right? Any help or suggestions will be greatly appreciated!
Here's my Javascript:
<script>
console.log("hello_List!")
function getSearch() {
console.log($("#query").val())
console.log(typeof($("#query").val()))
$.ajax({
type: "POST",
url: "./Search",
data: $("#query").val(),
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert("Success!");
console.log(response);
}
</script>
Here is my C# function, which is in the same folder as my javascript file:
public class UsersController : Controller
{
[HttpPost]
[System.Web.Services.WebMethod]
public JsonResult Search(string query)
{
List<EntityModels.AspNetUser> users = new List<EntityModels.AspNetUser>();
users = db.AspNetUsers.Where(x => x.Email.StartsWith(query)).ToList();
List<SelectListItem> userObjs = new List<SelectListItem>();
foreach (var user in users)
{
var userObj = new SelectListItem
{
Value = user.Id.ToString(),
Text = user.Email
};
userObjs.Add(userObj);
}
return new JsonResult()
{
Data = userObjs,
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
};
}
}
thanks for help! I've found the solution now, it's the data.
Instead of simply input a string, json with index and value work in this case.
So I changed the data attribute to:
data: { query: $("#query").val() },
This solved the problem
$.ajax({ type: "POST",
url: "./Search",
data: $.("#query").val(),
dataType: "json",
success: function(response){
//your success method code
goes here
}
,failure: function (response) { alert(response.d); } });

Sending a string with Ajax to controller

My knowledge of Spring boot is very low.
I have made a table in HTML, which when I click on, an event is sent to a Javascript function, in which I try to catch the Id (a string) of the cell and send it to the controller. I tried many examples from internet but none worked for me, can anyone help me please?
The id is being caught correctly by mouse click, but I have a problem with sending.
This is my JSP
<c:forEach items= "${rooms2}" var="m" >
<tr>
<td style="background-color:OldLace">${m.day }</td>
<c:choose>
<c:when test="${m.hour1confirm==false}">
<td style="background-color:green" id="${m.hour1}" onclick=
"content(this)" >${m.hour1 }</td>
...
<script >
// <script type="text/javascript">
function content(elem)
{
// $(document).ready(function()
// {
// // PREPARE FORM DATA
// var idt =elem.id;
// console.log(idt);
// // DO POST
// $.post({
// type : "POST",
// url :"reservation2",
// // contentType: "application/json",
// data : JSON.stringify(idt),
// dataType : 'json',
// })
// });
var idt =elem.id;
console.log(idt);
$.ajax({
url:"reservation2",
type: 'POST',
data: idt,
dataType: "text",
contentType: false,
mimeType: false,
success: function(response){
console.log(data);
return false;
}
});
}
</script>
this is controller
.
.
.
// #RequestMapping(value = "/reservation2", method = RequestMethod.POST)
// public String reservation2(#ModelAttribute("idt") String idt , Model model) {
// return "Reservation2";}
#RequestMapping(value = "/reservation2", method = RequestMethod.POST)
public #ResponseBody
String Submit(#RequestParam("idt") String idt) {
// your logic here
return "reservation2";
}
#RequestMapping(value = "/reservation2", method = RequestMethod.GET)
public String reservation(Model model) {
List<Room> rooms2= new ArrayList<>();
System.out.println(rooms2);
rooms2= x.findAll();
model.addAttribute("rooms2", rooms2);
return "reservation2";
...
when I run I get this error in console :
POST http://localhost:8080/reservation2 403 ()
I believe you are not sending the right parameter along the way. When you do the ajax post request, in the field data can you specify the name of the parameter you are sending?
Can you try this one
$.ajax({
url:"reservation2",
type: 'POST',
data: {"idt": idt},
dataType: "json",
contentType: "application/json",
success: function(response){
console.log(data);
return false;
}
});
Try changing your request to something like this
$.ajax({
url: "/reservation2", //added '/' in the beginning
type: 'POST',
data: idt,
dataType: "text",
contentType: "text/plain", //change
//mimeType: false, //remove
success: function(response) {
console.log(data);
return false;
}
});
and your controller to this
#RequestMapping(value = "/reservation2", method = RequestMethod.POST)
public String reservation2(#RequestBody String idt)
{
// your logic here
return "reservation2";
}

ASP MVC basic AJAX Json request returns null

I have an MVC application with a controller named Angular (I use AngularJS as well), which has an action called GetQuestion. That action returns a JsonResult which looks like this (grabbed from Chrome):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
My JS function is like this:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
But instead of the Json I wrote above, alert window only says [object Object]
Update
Ok, that was fixed, thaks. However as you may suspect, my goal is not to present this data in alert box, but use it somehow. So here's my controller in Angular
function QuestionCtrl($scope) {
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
And then the view:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
#using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
And I don't have neither image or the questions. If I hardcode them in controller then it's ok.
An alert will show that, i would suggest using console.log(data)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
or as the comments states:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
I resolved my second problem like this:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
Note that it's AngularJS.
The reason it's happening is because JSON is an Object in JavaScript. When you type
alert(data);
It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.
To view the contents of an object you can write a simple function to use with an alert or console.log.
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
And use it like this
alert(outputProperties(data));
For starters... when ever you are dynamically building the src url for an image (using the {{expression}} syntax from Angular) you need to not use the "src" attribute and use the "ng-src" angular directive. It allows angular time to process your url before the image is loaded.

Categories