Access row data via client side API of GridView - javascript

I have a DevExpress GridView in my Asp.NET MVC 4 application and want to access row data on the client side via JavaScript. At the moment I am doing the following:
Specify which values should be transmitted to js function ChangeDetailsTab:
function OnGridFocusedRowChanged(s, e) {
s.GetRowValues(s.GetFocusedRowIndex(),
'MOL_REGID;BATCH_NAME;MOL_NAME;MOL_ENTERED_BY;', ChangeDetailsTab);
}
Access values from array received by ChangeDetailsTab:
function ChangeDetailsTab(rowData) {
var molRegId= rowData[0];
var batchName= rowData[1];
var molName= rowData[2];
var molEnteredBy= rowData[3];
}
This approach makes it quite bad to access a large number of values or add/remove values later because the column names have to be specified in one large string (see example 1 line 3).
Has anyone a better solution for this problem?

The client-side GetRowValues is specially designed for this purpose.
I believe it is the best solution.

this is best way,Of course a any way for this,you can called in C# Code,in CustomCallback you can run it,in client side on the javascript you can perform,such
ASPxGridView1.PerformCallback()(ASPxGridView1 has a event that named CustomCallback)with this you without reload page can get value of C# code
in C# Code :
ASPxGridView1.GetRowValues(ASPxGridView1.FocusedRowIndex,"column1","column2",....)
of course you remember that should called this event from java script in client-side

Which method is faster? I'm loading multiple values but it seems slow for some reason.
I'm doing the setup similar to what you have but I have about 25 - 30 values being loaded.
function insuranceselectionchange() {
insuranceselection.GetRowValues(insuranceselection.GetFocusedRowIndex(), 'CarrierName;CarrierAddress;CarrierAddress2')
}
function SetInsuranceValues(values) {
CarrierName.SetText(values[0]);
CarrierAddress.SetText(values[1]);
CarrierAddress2.SetText(values[2]);
}

Related

Blazor server side problem share javascript code

I'm developing my project with Blazor Server-side.
While I develop, I used javascript code to implement things that hard to implement by C#.
However, I'm facing something weird situation. (I guess it is problem for javascript)
Suppose there are 2 users(A, B). When 'A' user do some action that call javascript code, if 'B' user into same page, 'A' users action affects to 'B' user.
I implemented web page that have 3d scene with threejs. As I explained above, when User 'A' move some object with mouse event(mousemove, mousedown..), if User 'B' accesses the same page, 3d objects of B are moved to the location where User 'A' moved.
Originally, when user access to web page I developed, 3d objects's position should be 0,0,0.
My Guess
I don't use prototype or class(use variable and functions globally. I'm new to javascript.. )
Javascript runs on server-side(share resources??, If then, how can I solve it)
I'm guessing the javascript would be problem, but if you have any other opinions, would you please share?
Edited
I've solved this problem using DotNetObjectReference.Create(this);
C#
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
//send created instance to javascript
var dotNetObjRef = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("SetObjectRef", dotNetObjRef);
}
await base.OnAfterRenderAsync(firstRender);
}
[JSInvokable]
public async Task enableSomething(bool bEnable)
{
var something = bEnable;
}
//== before edit
//[JSInvokable]
//public static async Task enableSomethingStatic(bool bEnable)
//{
// var something = bEnable;
//}
Javascript
var objectRef;
function SetObjectRef(ref) {
objectRef = ref;
}
//call c# function
objectRef.invokeMethodAsync("enableSomething", true);
It was problem of 'static' method as I guessed.
If you declare C# method called from javascript as 'static' and this method changes something of UI variable, this method can affect another users.
So I create instance of current page and send it javascript and when I need to call C# methods from javascript, I call methods using created instance.
Is there any problem or issue, please share it.
Sorry for my bad English.
JavaScript runs client side only. I don't see how two windows, let alone two users, would share data.
Almost for sure, the problem is that you are injecting a singleton service-- which means the server will use one instance for all users.
If so, you have two choices:
(1) add logic to your singleton service to incorporate users. (For example, a dictionary with UserID/Property name for key, and a column for Value)
(2) go to Startup.cs and change the suspect singleton service to .AddScoped(), which will create a new instance for each user.
For right now, I think the latter solution will solve your problem immediately. However, don't underestimate the value of Singletons-- they'll be very useful for other things.

my jQuery parameter is not recognized by the C# method in which is accessed in script area

I tried to access the my C# method in my JavaScript, but this method is not accepting the local parameters and saying, the parameter does not exist in the current context.
var typeofServiceNumber = $("#serviceType").val();
#MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber));
The above typeofServiceNumber is not recognized by the method
Razor code is executed server side before the HTML is returned in the response stream.
Javascript is executed client side within the resultant HTML.
Therefore you cannot pass a Javascript variable through to a Razor method, and you receive the message that typeOfServiceNumber is not recognized.
To be recognized, it would either need to be handled server side via data being passed to the View (ViewBag, Model etc), or it would need to be declared and assigned to within Razor tags on the page itself.
EDIT: to clarify the last point:
var typeofServiceNumber = $("#serviceType").val();
#MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber))
The first line you have here is all happening in the browser of the end user.
The second line is all happening on the server. You see the error message because you are trying to pass "typeofServiceNumber" to your method, and the variable isn't even declared at that point.
Without knowing exactly what you're trying to achieve it's hard for me to give a precise answer as to how to solve your problem. But here are two possibilities:
1) You know what $("#serviceType").val() is going to be before you serve the web page to the end user because that value is being set server side.
Controller:
public ActionResult MysteryController()
{
...your code here to work out what the service type is...
ViewBag.serviceType = serviceType;
return View();
}
View:
...lots of lovely html and such...
<script>
#MyStaticClass.StringEncoding(Convert.ToString(ViewBag["serviceType"]));
</script>
I can't see what the output of #MyStaticClass.StringEncoding() is but I have to assume at this point that it is doing whatever it is supposed to do.
Although the logic is split between the controller and the view, all of this is happening server side.
The second half of my point "or it would need to be declared and assigned to within Razor tags on the page itself." refers to the fact that one variation of this method could involve manipulating data in the View itself by enclosing it in a Razor code block like this:
#{
var typeofServiceNumber = #MyStaticClass.StringEncoding(Convert.ToString(ViewBag["serviceType"]));
}
The alternative, which I did not really address originally is:
2) You don't know what the value of $("#serviceType").val() is going to be before the page is loaded because it is being set by the end user and your function needs to be used before the data is submitted to the server:
If that's the case then #MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber)) is no good to you, you will have to replicate the function in JavaScript and include it in the webpage itself.

pass data from javascript to asp.net core 2 razor page method

Is there any to pass some data from HTML property on changed event data to asp.net core razor pages?
I want to get an ID from dropdown list from HTML using JS and pass it to Razor Pages (asp.net core 2) and get the result from the custom method ?
Code I want to be look like below if possible :)
JS code
$('#Neighborhood_DistrictId').on('change', function () {
#Model.GetDistrictName($('#Neighborhood_DistrictId').val());
});
On the Razor page
public string GetDistrictName(Guid id)
{
return httpSystemApi.GetByIdAsync<District>("Districts", id).Result.Name;
}
GetDistrictName method is connecting to API and returning the value. I don't want to direct connect to API with JS if there is a way to do what I want
I am playing around with Razor Pages, and I have the same issue. Below is my work around. It seems like there should be some event handler will do the same thing, but I have not found another way yet. I tried treating it like the MVC controller, but I believe there is some form token that it is expecting so that did not work [name="__RequestVerificationToken"].
Basically what I am doing here, is tricking the page into thinking I clicked a button and then telling it which function to look at. Additionally, you have access to all your model fields so you do not need to pass them.
Here is the select list:
<div class="col-md-2"><select id="ddlPortalName" asp-for="selectedPortalName" asp-items="Model.portalNames" onchange="ConcatenateURL();"></select></div>
And then here is the JS function, notice I had to change the form action to tell it which page function to look at.
<script type="text/javascript">
function ConcatenateURL() {
document.forms[0].action = "VisibilityTest?handler=ConcatURL";
document.forms[0].submit();
}
</script>
And then finally here is the c# file method.
public void OnPostConcatURL()
$('#Neighborhood_DistrictId').on('change', function () {
#Model.GetDistrictName($('#Neighborhood_DistrictId').val());
});
#Model.GetDistrictName is a server side method not Usage directly inside script
$('#Neighborhood_DistrictId').on('change', function () {
var url="http://localhost/{controllername}/{methodname}/id=";
url=url+$('#Neighborhood_DistrictId').val()
$.get(url,function(data){
...some code
});
});
var url="http://localhost/{controllername}/{methodname}/id=";
In mvc 5 genrate url from server side and set the client side variable
var url='Url.Action("{action}","{controllername}","actionname")';
this is only way for call the controller using javascript or jquery not Directly use server side method in javascript.

Using ordinary JavaScript/Ajax, how can you access rows and columns in a Sql DataTable object returned by a VB.Net web service?

Let's say you have a VB.Net web method with the following prototype:
Public Function HelloWorld() As DataTable
Let's say you have that returned to you in ordinary JavaScript/Ajax. How would you get individual rows out of it, and how would you get individual fields out of those rows (at least assuming it comes from an SQL query - I'm not sure if it makes a difference)? I'm not casting it into any particular type before it gets passed to the success function. To illustrate what I'm talking about, it would be kind of like doing this in AS3:
for each (var table:Object in pEvent.result.Tables) {
for each (var row:Object in table.Rows) {
ac.addItem(row["id"]);
}
}
except that I'm not necessarily looking to loop through them like that - I just want some way to get the information out of them. Thanks!
EDIT: For example, say you have the following function in a VB.Net web service:
<WebMethod()> _
Public Function Test() As DataTable
Return DBA.OneTimeQuery("SELECT id FROM visits WHERE id = 13")
// returns a one-row, one-column DataTable with the id field being set to 13
End Function
How would you be able to get 13 out of it once it gets into the JavaScript that's calling the web method? Everything I try just says "[object]".
You do not want to return a DataTable object in your web method. The best approach would be to develop a REST web method that returns JSON that represents the data you want to return, as JavaScript will be able to work with JSON directly. Here is a QA the directs you on how to do this. This is if you are using WCF, which it appears you are. I find it better to use ASP.NET Web API for RESTful web services.

How to get texts from Resx to be used in Javascript?

We are building large ASP.NET applications for the intranet use in multiple languages/cultures. We utilize the Globalization with RESX files and use GetResourceText on the server side to get the localized texts.
Lately we are doing more and more client side logic with JQuery.
How do I get the RESX texts to be used in Javascript?
e.g. texts used for validation, dynamic messages etc.
All our Javascripts are in .JS files, we do not want to mix HTML in the ASPX page and Javascript blocks.
Thanks for your help.
Unfortunately, in an external JS file the server side code is not being processed by the server. However I have seen a workaround where you can set your translated values in hidden fields on the page - this way your javascript will be able to read the values in.
For example:
<%-- This goes into your page --%>
<input type="hidden" id="translatedField" name="translatedField" value="<%=Resources.Resources.translatedText %>" />
and use this inside your javascript file:
// This is the js file
$(document).ready(function() {
alert($("#translatedField").attr("value"));
});
You will be able to separate the values and still see it in your external JS file.
There is also another workaround that creates a .aspx file that only outputs Javascript instead of HTML. Check out the link below:
Using server side method in an external JavaScript file
Always separate functionality from human readable strings.
If you're creating jQuery-plugins you should be able to pass an array of localized strings as parameter when you call your different jQuery functions. The array could be defined as inline javascript directly on the page calling the different jQuery plugins or you could load the from external resource in the format /scripts/localization/strings.js?ci=en-US and register a Generic ASP.Net Handler in web.config that would respond to scripts/localization/strings.js
The DatePicker control is a fine example of how to localize text for the jQuery datepick control - this js file is dynamically created from resource files (resx) and when included on a page it will make sure the calendar control will have danish text.
Create a HttpHandler (.ashx file), and return JSON with your text resource strings.
You may also "publish" it to global namespace, i.e.
Response.Write("window.Resources=");
Response.Write((new JavaScriptSerializer()).Serialize(strings));
set up HTML like:
<script src="Resx.ashx?lang=en-US" />
<button class="LogoutButtonResourceId OtherButtonClasses">(generic logout text)</button>
<a href="#"><span class="SomeLinkTextResourceId OtherClasses">
(generic link text)
</span></a>
and apply texts like this:
$(document).ready(function() {
for(var resId in Resources){
$("."+resId).html(Resources[resId]);
}
});
If you don't want to use ASP.NET to generate your main JavaScript, here are two other options:
Use ASP.NET to generate a script file that contains variable-to-string assignments, such as var mystring = 'my value';. Your main script would then reference the localized text with variables names rather than as embedded values. If that's still too "dirty" for you, you could encode the strings as JSON rather than as variable assignments, using an HttpHandler rather than straight .aspx.
Have your JavaScript code issue an Ajax call to retrieve an array or list of localized strings from the server. The server-side part of the call would retrieve the text from your resx files.
Have you considered using $.ajax in combination with ASP.NET WebMethods? It's hard to suggest a more concrete solution to this problem without understanding how your JavaScript/jQuery would consume/process the resources. I assume that they're organized into logical groups (or could be) where you could return several resource strings that belong on a single page.
Assuming that, you could write a very simple C# class -- or use a Dictionary<string, string> -- to return data from your ASP.NET WebMethod. The results would look something like:
[WebMethod]
public Dictionary<string, string> GetPageResources(string currentPage)
{
// ... Organizational stuff goes here.
}
I always separate out my AJAX calls into separate .js files/objects; that would look like:
function GetPageResources (page, callback)
$.ajax({ // Setup the AJAX call to your WebMethod
data: "{ 'currentPage':'" + page + "' }",
url: /Ajax/Resources.asmx/GetPageResources, // Or similar.
success: function (result) { // To be replaced with .done in jQuery 1.8
callback(result.d);
}
});
Then, in the .js executed on the page, you should be able to consume that data like:
// Whatever first executes when you load a page and its JS files
// -- I assume that you aren't using something like $(document).ready(function () {});
GetPageResources(document.location, SetPageResources);
function SetPageResources(resources) {
for (currentResource in resources) {
$("#" + currentResource.Key).html(currentResource.Value);
}
}
I know it's to late but want share my experience in this task)
I use AjaxMin. It can insert resx key values into js file on build event.
It's not common way but it keeps html without unneeded script blocks and can be done during minification process if you have it.
It works like this:
ajaxmin.exe test.js -RES:Strings resource.resx -o test.min.js
Also you need to do the same for ech locale if you have many.
Syntax to write resource keys in js (and also css) is written here:
Js localization
Css localization
How about injecting it as part of a javascript control initialization? what i do is as follows:
I have a self-contained javascript control - call it CRMControl, which has an init method called setupCRMControl, to which i pass a settings object. When i initialize it, i pass an object containing all the resources i need inside javascript as follows:
CRMControl.setupCRMControl({
numOfCRMs: 3,
maxNumOfItems: 10,
// then i pass a resources object with the strings i need inside
Resources: {
Cancel: '#Resources.Cancel',
Done: '#Resources.Done',
Title: '#Resources.Title'
}
});
Then, inside this javascript control:
var crmSettings = {};
this.setupCRMControl(settings) {
crmSettings = settings;
};
and whenever i want to show a resource, i say (for example, show an alert saying 'Done'):
alert(crmSettings.Resources.Done);
You can call it "R" to make it shorter or something, but this is my approach. Maybe this may not work if you have a whole bunch of strings, but for manageable cases, this may work.

Categories