Get a resource string based on javascript value - c#

Is it possible to accomplish something like this?
<script type="text/javascript">
function getValues( keysArray ) {
var valuesArray = new Array(keysArray.length);
for (var i = 0; i < keysArray.length; i++) {
valuesArray[i] = #this.LocalResources(keysArray[i]);
}
return valuesArray;
}

getValues function will get executed on the browser. Razor is going to execute before the page is send to the browser. there for this wouldn't work.
If you wanted to call the LocalResources method on the server you could to expose a controller action and perform a ajax request from the client.
Perhaps something like this on the browser:
Javascript
function getValues( keysArray ) {
$.ajax({
url: "/Controller/getValues",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify({ "keysArray" : keysArray }),
success: function (result) {
//result obj is your array of resources
}
});
MVC Controller
public JSONResult getValues(object keysArray)
{
///Build respurce array here
}

Ajax request, or;
loading the list of necessary Resources keys in page and then accessing them by JS.

Related

ajax request to razor page using handler

I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});

Pass array to Controller Action via AJAX

I saw similar questions, but none helps me.
I have the simplest code:
public JsonResult JsonGetStatesInfo(object[] instructions)
{
if (Request.IsAjaxRequest())
{
return Json(String.Empty);
}
else
throw new NoAjaxRequestException();
}
and client side:
var instructions = [];
instructions.push('abc');
instructions.push('ddd');
instructions.push('assdbc');
var inst = JSON.stringify(instructions);
$.ajax({
cache: false,
data: { 'instructions': inst },
traditional: true,
dataType: 'json',
url: '/State/JsonGetStatesInfo',
type: 'post',
success: function (resp) {
},
error: function (data) {
alert(data.error);
}
});
On client side I tried with JSON.stringify, without JSON.stringify, with traditional: true, without traditional: true
On server side I tried as parameter : object[], object, List< object >, List< string >, IEnumerable< string > etc
Nothing worked! How to do it correctly?
SOLVED:
My problem was trivial - one from real values of array had HTML Tag. Just need add [ValidateInput(false)] to action method
You just need the following settings:
Pass array of string to a MVC Action by Ajax:
Controller:
public JsonResult MyAction(string[] instructions)
{
// Your codes
}
View:
$.ajax({
data: { 'instructions': ['abc', 'dcs', 'arr'] }, // << Without JSON.stringify
traditional: true, // << Important line
url: '/State/MyAction',
type: 'post',
dataType: 'json',
success: function (resp) {
// Your codes
}
});
Using contentType: "application/json; charset=utf-8" is recommended too.
Pass array of int to a MVC Action by Ajax:
Also I use bellow codes to path an array of int to an Action
Controller:
public JsonResult MyAction(int[] instructions)
{
// Your codes
}
View:
$.ajax({
data: { 'instructions': [1, 2, 3] }, // << Without JSON.stringify
traditional: true, // << Important line
url: '/State/MyAction',
type: 'get',
dataType: 'json',
success: function (resp) {
// Your codes
}
});
public ActionResult JsonGetStatesInfo(string[] instructions)
{
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = instructions.Length}
};
}
Client side
var instructions = ['abc', 'dcs', 'arr'];
$.post('/State/JsonGetStatesInfo', { instructions: instructions },
function (data) {
if (data.result!= null && data.result!= undefined) {
alert(data.result);
}
});
Try this...
At least, you can pass javascript array as a string and deserialize it in the controller
public JsonResult JsonGetStatesInfo(string instructions)
var instructionsArray= JsonConvert.DeserializeObject<string[]>(instructions);
Or use new Array like explained here : https://stackoverflow.com/a/310136/3063094
Try adding:
contentType: "application/json; charset=utf-8"
To you AJAX call, And please delete the:
JSON.stringify(instructions);
Because you are trying to stringify an object, which will be sent to the server as a string rather than an object (and the server side expects an object).
you can also delete the
traditional: true,
ache: false,

ajax post data is null in controller asp.net mvc 5

I try to send a JSON object back to the server. This is my AJAX call
function SaveData() {
var model = []
debugger
$.each($('.Money'), function (i, item) {
model.push({
Money: $('.Money').eq(i).val(),
Day: $('.Day').eq(i).val(),
Note: $('.Note').eq(i).val()
});
})
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: { partnerDeposit: JSON.stringify(model) },
type: 'POST',
dataType: 'json',
succsess: function () {
}
})}
This is the method in the controller which is being called:
enter image description here
https://i.stack.imgur.com/FqEt9.png
The problem I have is that always the json variable from above is an empty object. The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong. Thank you.
Try adding the partnerDeposit to the JSON.stringify call like this:
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: JSON.stringify({partnerDeposit: model}),
type: 'POST',
dataType: 'json',
succsess: function () {
}
})
I haven't found this answer anywhere else so I had to discover it through experimentation. Hopefully this will help someone.
You'll find that in your controller, it's receiving a Request.Form object and if you look in Request.Form[0] you'll find your data. The reason that there's data in the form but MVC is seeing it as null is that the key to the form element being POSTed is "" (blank).
So client side, you have to set content type properly, and precede your data with something like "myData=" + JSON.stringify(myJSONObject), where "myData" is the key name you are adding, like so:
$.ajax({
type: "POST",
url: URL,
data: "myData="+JSON.stringify(myJSONObject),
contentType: "application/x-www-form-urlencoded; charset=utf-8"
On the server side, your [HttpPost] endpoint has to have as its input a variable with the same name as the key you declared in your AJAX, like so:
`
[HttpPost]
[Authorize]
public ActionResult Index (string myData) // <-- var name matches AJAX
{
// de-serialize data into server-side object using
// JSONConvert.DeserializeObject
}
`

.JQuery .ajax how do I call WCF method with return value?

I have been able to call WCF methods with .ajax. How do I call a method that returns a value? I need to call this method to see if data is ready and if not wait one second. The WCF method is:
[OperationContract]
[WebGet]
public bool IsDataReady(string requestGUID)
{
if (Global.publicDataDictionary.Keys.Contains(requestGUID))
return true;
else return false;
}
My JavaScript so far is:
$(document).ready(function() {
var input = {requestGUID:"<%=guid %>"};
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function(data) {
}
});
EDIT2: I broke out the 2nd ajax call into a method but my logging is showing that the call to 2nd web service never passes a requestGUID. Can't i use the same input variable?
var guid = "<%= this.guid%>";
// var input = '{"SbiId":"' + guid + '"}';
// var input = {requestGUID:"ca222cf7-be5e-431a-ab93-9a31e8ae2f4a"};
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
EDIT2: I broke out the 2nd ajax call into a method but my logging is showing that the call to 2nd web service is never getting called:
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
else {
//Continue as data is ready
callUpdateGrid(input);
}
The return value will be contained in the data parameter passed to the success callback setup in your ajax call.
You will need to check the value here, then if false, setup a timeout, which on expiry will attempt the ajax call again.
It would be best IMO to wrap up the Ajax call inside a function, that you can call in a recursive fashion when the timeout has expired. e.g.
function CallIsDataReady(input){
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function(data) {
if (!data){
setTimeout(function(){CallIsDataReady(input);}, 1000);
}
else{
//Continue as data is ready
}
}
});
}
$(document).ready(function() {
var input = {requestGUID:"<%=guid %>"};
console.log(input);
CallIsDataReady(input);
});
When you view source on this page is:
var input = {requestGUID:"<%=guid %>"};
showing correctly in the javascript? If you put a breakpoint in your IsDataReady method, do you see if requestGUID has a value? Is your service on the same domain as the page calling it?
EDIT:
In your service change: [WebGet]
to:
[WebGet(
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json]
Read up on RESTful web services:
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide

How can Usercontrol access the Webmethod using Jquery and Json

$(document).ready(function () {
//hide the branch
var noteServiceUrl = "../../../AJAX/Common/BankingServiceAjax.svc/";
var proxyNotes = new serviceProxy(noteServiceUrl);
OnGetNotes();
function OnGetNotes() {
proxyNotes.invoke("SearchBranchesByBankID",
{ "request":
{
"BankID": 1
}
}, OnGetNotesComplete, OnError);
}
function OnGetNotesComplete(result) {
var obj = jQuery.parseJSON(result);
var notes = obj.Notes;
}
I cannot access the BankingServiceAjax.svc by usercontrol, But if do this in page, I can access the Service. The URL is correct I think I lack only one attribute that might access the BankingService in my Usercontrol.
it is going to be done in an AJAX call similar to this
$.ajax(
{
type: "GET",
url: 'http://fastmotorcycleservice.cloudapp.net/FastMotorcycleListService.svc/list/Bruno',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
Google is good too - How To Consume svc Webservice using jQuery

Categories