JavaScript: Multiple parameters in __doPostBack - javascript

First of all, the only post (calling-multiple-dopostback-from-javascript) I found about this didn't help my problem, so I don't belive this post is a duplicate.
I have this JavaScript function in my ASPX webpage that includes a __doPostBack function:
function OpenSubTable(bolID, controlID) {
// code
__doPostBack('UpdatePanelSearch', bolID);
// more code
}
Works perfectly and I can get the value of bolID into my code behind like this:
protected void UpdatePanelSearch_Load(object sender, EventArgs e)
{
var bolID = Request["__EVENTARGUMENT"];
// code
}
The problem is, that I have to pass 2 different values through the postback. Are there any simple solutions to this? Obviously something like this doesn't work:
function OpenSubTable(bolID, controlID) {
// code
__doPostBack('UpdatePanelSearch', bolID, controlID); // not that simple, i'm afraid :(
// more code
}
Any help would be most welcome.
Regards,
Gunnar

You could pass the two values as one JSON string:
function OpenSubTable(bolID, controlID) {
__doPostBack('UpdatePanelSearch', JSON.stringify({ bolID: bolID, controlID: controlID}));
}
And then parse it on the server:
protected void UpdatePanelSearch_Load(object sender, EventArgs e)
{
SomeDTO deserializedArgs =
JsonConvert.DeserializeObject<SomeDTO>(Request["__EVENTARGUMENT"]);
var bolID = deserializedArgs.bolID;
var controlID = deserializedArgs.controlID;
}
public class SomeDTO
{
public string bolID { get; set; }
public string controlID { get; set; }
}
If you're using .Net >=4.0, I believe you can deserialize to a generic touple and avoid having to create SomeDTO. Edit: More information about deserializing to dynamic types.

Consider placing your data in server side hidden fields and then reading that data after your postback.
<asp:HiddenField id="Data1HiddenField" runat="server" />
<asp:HiddenField id="Data2HiddenField" runat="server" />
Your client script should include the ClientID values to handle server side naming container modifications. Using the <%= expression %> syntax (Expression Builder) requires that your script (or at least this part of the script) be maintain within your .aspx file. If you maintain your JavaScript in external files, you can "register" a simple function that gets called by your main JavaScript to move the data and compose that function server side along with the required ClientIDs. See ClientScriptManager.RegisterClientScriptBlock().
var data1 = "data value 1";
var data2 = "data value 2";
$("#<%= Data1HiddenField.ClientID %>").val(data1);
$("#<%= Data2HiddenField.ClientID %>").val(data2);
Your server side code then looks like this:
string data1 = Data1HiddenField.Value;
string data2 = Data2HiddenField.Value;
There are certainly other techniques to passing multiple data values but I have found this to be both simple and easy to maintain. You can pass all kinds of data and encode it using JSON if needed.

I have used multiple parameters before by building and splitting a string.
eg
string args = String.Format("{0};{1}", bolID, ControlID);
You can then pass this in to the arguments for the postback, and when checking for the postback arguments just split the string based on your speration character (in this case ';')

Related

How to pass entire ViewModel into External Javascript file in .net core mvc 3.1?

I would like to pass my entire ViewModel from a .cshtml file into an External Javascript that is included in the same cshtml file.
I have tried different solutions but none of them work. I first started with reguarl js variable in cshtml file and passed it into the external js file.
E.g for the below code when I click on the below button I get, Uncaught ReferenceError: myValue is not defined
**- in test.cshtml file:**
<button onclick="testAlert()"></button>
<script language="text/javascript">
var myValue = "myValue test";
</script>
<script src="~/js/test.js"></script>
**in test.js:**
/**
* This is a test alert function in external js.
* */
function testAlert() {
console.log(myValue);
}
The above is just a test for regular variables which if when it works, then I would like the below object in the external javascript like below.
***in test.cshtml:***
var customer = #Html.Raw(JsonConvert.SerializeObject(Model.CustomerDetails));
***Then in test.js***
function testAlert() {
console.log(customer.Names.FirstName);
}
As far as I know, if you want to pass the model to JS scripts, I suggest you could use #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(object model)) to convert the model to a json string as #Seabizkit suggests. Then you could convert this json to model in the js and read its property.
More details, you could refer to below codes:
Model class:
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public string SemesterNumber { get; set; }
}
In your view set a button like below:
<input type="button" onclick="testAlert()" value="test" />
Then add a script at cshtml like below:
#section scripts{
<script>
// Notice: we should add '' between the html.raw to set it as a json string.
var customer = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))';
</script>
}
Then in the another js file add below codes:
Since my model is just a simple model like this to test, if you want to use my codes, you should modify it.
function testAlert() {
console.log(customer);
var ce = JSON.parse(customer);
alert(ce.SemesterNumber);
}
Result:
i think.... you lookng for
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
so in your case something like
function testAlert() {
var customer = #Html.Raw(JsonConvert.SerializeObject(Model.CustomerDetails));
var customerJson = JSON.parse(customer);
console.log(customerJson.Names.FirstName);
}
I got my own answer but was not fully satisfied with it yet, so didn't post until today.
Need more refinement though.
test.cshtml:
#using Newtonsoft.Json;
<script type="text/cshtml">
viewmodel = #Html.Raw(JsonConvert.SerializeObject(Model));
</script>
test.js:
at the top:
var viewmodel;
Only by doing this does it work correctly. Most similar to #brando Zang's answer except for the extra initializing part. Still not sure why it works without var or let in the main cshtml page.
Also, intellisense is not working yet on my external js file test.js.
But thanks a ton to Brando Zang and Sea Bizkut for taking the time to help me out.
Some findings which will be useful for other people:
In default .net core mvc 3.1 , the default json is automatically converting viewmodel values to camelcase from pascal case, so using newtonsoft instead keeps default functionality and naming conventions.
Can do it for default JSon parser itself in startup itself but it is a hassle, so using Newtonsoft instead.
Also for enum values, it takes the value and not the string by default. so in the model. e.g in js object for CustomerType you will get 0,1,2 instead of Standard, Premium or VIP. so to fix it,
(VB syntax below for enum - not able to show code indented properly in SO)
Public Enum CustomerType
Standard = 0
Premium = 1
VIP = 2
End Enum
TestModel.cs:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
[JsonConverter(typeof(StringEnumConverter))]
public CustomerType CustomerType;

Strange anamoly in ASP.NET Web Forms (code not working with no errors ...)

I'm facing a strange anomaly in C# (ASP.NET Web Forms).
I have an ascx Web Page where I call a function creating a JSON from localStorage values.
function creerJsonDepuisLocalStorage() {
var modif = {}
// Filling modif with localStorage values ...
try {
return JSON.stringify(modifs);
} catch (e) {
console.log(e);
return "";
}
}
My codebehind is called on submit button click and recover the JSON to use it.
protected void btnEnregistrerFiche_OnClick(object sender, EventArgs e)
{
// tons of code ... doing various things like !!DataBase access!!
string argument = Request.Form["__EVENTARGUMENT"];
JavaScriptSerializer ser = new JavaScriptSerializer();
try
{
FicheModifiee edits = ser.Deserialize<FicheModifiee>(argument);
// edits treatments, commented for debug
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
// some other code like !!UI update!!
}
My problem is the following :
When my front end javascript function returns an empty string, the codebehind function works like a charm, doing database modifications and updating UI.
When my front end javascript function returns a real object, the codebehind function is correctly deserializing the JSON into the edits class and I don't have any bug or crashes BUT database access isn't made and UI is updating with previous data (not considering any changes made before submitting).
This sounds like dark magic as I'm not getting any crashes and my little piece of code isn't doing anything with the rest of the function ...
Thanks for your help.
I managed to fix my problem by using an asp:hiddentField (set at the end of my json creation script) and by reading it directly from C# code. Still not knowing what happend with Request.Form["__EVENTARGUMENT"];

Passing Code as String

I have created a Web API that will receive Input from Jquery and will use this input to dynamically alter a string that's stored in a resource file.
This String happens to be an almost complete piece of vbscript code that I plan on passing back down to my website.
My problem is that the resource automatically "stringifies" the Code and the output is flooded with escape characters which renders it completly unusable as actual code.
Is there a way to store the code in a way that makes escape strings unneccesary while still enabling me to alter it similiar to "if it were a string" and pass it down to my Website?
The goal is to then use Jquery/Javascript to make this code into an actual vbscript file and let the user download it.
As per request here some Code.
public string GetDeployment(Deployment deployment)
{
string vbs = Resource1.vbs;
vbs = vbs.Replace("%environment%", deployment.SystemKind);
vbs = vbs.Replace("%platform%", deployment.PlatformKind);
vbs = vbs.Replace("%application%", deployment.ApplicationName);
vbs = vbs.Replace("%config", deployment.ConfigInfix ?? "Null");
vbs = vbs.Replace("%subFolder%", deployment.subFolder ?? "Null");
return vbs;
}
This method alters the vbscript depending on the Input. The API itself receives a JSON with Data for all the properties of deployment.
public class DeploymentController : ApiController
{
private DeploymentRepository DeploymentRepository;
public DeploymentController()
{
DeploymentRepository = new DeploymentRepository();
}
[HttpPost]
public string Post([FromBody]Deployment deployment)
{
return DeploymentRepository.GetDeployment(deployment);
}
}

Trying to access server side variable from javascript

i have a page where in the form load i initialize a server side variable with value and i want to render that value in js section. i am working with asp.net webform apps.
my server side page load code
string errblankEmail ="";
protected void Page_Load(object sender, EventArgs e)
{
errblankEmail ="Hello World";
}
if (str == '') {
alert('<% =errblankEmail %>');
}
when i run the page then i am getting error message like
CS0103: The name 'errblankEmail' does not exist in the current context
and i also saw that my page_load is not getting called because i set break point there.
so guide me how to fix this problem. thanks
You have to make the variable public in order to access it.
public string errblankEmail ="";

Get data from JS variable and set in a ASP.NET variable

I want to pass data from one user control to another one, but i've tried several things to do it, and non of them worked, such as sessionStorage in JS, Session in ASPX, cookies in both of them.
This data is dynamic so I don't now how to transfer it, to the other user control.
I even tried to put aspx code in the javascript function (then when I click in the button it could trigger the code, but it doesn't work as well).
This button i refereed above is written in a literal control.
JavaScript Functions
this function is the LoadUsers UserControl
function getID(ID) {
sessionStorage.setItem("userID", ID);
}
this function is in the Access UserControl
function catchIP() {
var ID = sessionStorage.getItem("userID");
$('#<%= value.ClientID %>').val(ID);
}
UserControls
Load Users:
...
string _str = "<a href'#lastAccess' css='btn btn-success' onclick='javascript:getID(" + _id[_contForeach] + "); catchID();'>Access</a>";
_loadUsers.Controls.Add(new LiteralControl(_str));
Access:
How can I get access to the ID in the JavaScript function and apply it without using Page_Load
To pass information between the server side code and the client side code (JavaScript) use ajax
Ajax
So using jquery, have something like this function:
$.get('getuserid.aspx', function(response) {
//Do something with return response
});
then in the code behind getuserid.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
//set userid
Response.ContentType = "text/plain";
Response.Write(userid);
Response.End();
}

Categories