C# - Passing JSON Serialized Data Via Hidden Field?
Mar 2, 2011
In ASP.NET WebForms I want to pass arbitrary data from server to client and back again. I am serializing to JSON and have been simply producing JavaScript that creates the object on the client. I have no problem sending data to the server with ajax, but there are situations where I also want to send a Javascript object data back to the server on postbacks. So I guess it needs to be in a hidden field.
1) What is the best way to do this in terms of minimizing complexity and optimizing space and efficiency? In researching this I discovered Protocol Buffers but there does not seem to be a good C# implementation. I did find one, but it was a couple years old and self-described as buggy so that scared me.
2) If I just pass a JSON string, how can I be sure it will be safe to include as the value for a hidden field? Is there any reason I might not want to do this? I could Base64 encode, but it seems like this adds a lot of overhead. What is considered the best or preferred method?
View 1 Replies
Similar Messages:
Mar 26, 2010
I am trying to pass data from client to server using a hidden field. If I use a button, then OnClientClick sets the value, and OnClick does the postback and all is well.
However, I am responding to a Client event, and although this works I get no postback. How do I now force a postback from my client handler?
View 3 Replies
Mar 23, 2011
I have a custom user control which contains a asp hiddenfield object. The value of this hidden field is being set using javascript and I have verified that the value is being set properly. When a postback occurs the new value is not being saved and I cannot access it in my code.
I believe the problem is because the user control is not saved in viewstate and therefore the hidden field value is not saved accross postback. How can I make the hidden field save its value? I tried accessing it from the early page cycles and still no luck.
View 4 Replies
Jan 7, 2010
I have Gridview like this:
<asp:GridView ID="gvPartsSearchResult" runat ="server" CssClass="MRJ_TextGrid">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:RadioButton
ID="rdButton"
runat="server"
AutoPostBack ="true"
onclick="javascript:CheckOtherIsCheckedByGVIDMore()"/>
<asp:HiddenField
ID="hdnFileExtension"
runat="server"
Value ='<%#Bind("FILE_EXTENSION")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want to read the hidden field value when the user clicks on the radio button.
View 2 Replies
Jul 8, 2010
I have two parameters (categoryName and categoryDescription) that I need to pass to the web service using JSON. I found the syntax to pass categoryName but have not been able to get the correct syntax to pass both parameters. Here is the code.
<script src="js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
[code]...
View 4 Replies
Jun 22, 2010
I have successfully returned data from a ASP.Net webservice in JSON format (using a service method that required no parameters) but have struggled with making a webservice call that requires a parameter.
Webservice:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function TestWebService(ByVal Description As String) As Stock
Dim res As New Stock(Guid.NewGuid, Description)
Return res
[Code]....
View 1 Replies
Jan 24, 2011
I am using ASP.NET 2.0 and C#. I have a gridview, which has a datanavigateurlformatstring, in which i am passing data in the gridview as querystrings.I have a hiddenvariable in the page. i would like to pass the hidden variable to the gridview in the datanavigateurlformatstring.Currently i have the gridview and hidden variable like this:
[Code]....
How to pass the hiddenfield value in the datanavigateurlformatstring?
View 3 Replies
Dec 1, 2010
I have 2 classes that are used to mirror the data from an ajax call. One (Customer) contains a property which is name, and the other is an array of Products.
Public Class Customer
Private _Name as String
Private _Products as Product()
Public Property Name() As String
[Code].....
View 1 Replies
Mar 4, 2011
I have the following to get the Json abject passed from the controller and populate the various textboxes in the view. However, nothing is happening even though controller is passing a valid Json object. What is wrong with this code?
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var url = '<%=Url.Action("DropDownChange") %>';
$("#vendorID").change(function() {
var selectedID = $(this).val();
if (selectedID != "New Vendor Id") {
//$.post('Url.Action("DropDownChange","Refunds")', function(result) {
$.post(url, { dropdownValue: selectedID }, function(result) {
alert(selectedID);
$("#name").val(result.Name);
$("#city").val(result.City);
$("#contact").val(result.Contact);
$("#address2").val(result.Address2);
$("#address1").val(result.Address1);
$("#state").val(result.State);
$("#zip").val(result.Zip);
});
}
});
});
This is the code in my controller;
public JsonResult DropDownChange(string dropdownValue)
// This action method gets called via an ajax request
{
if (dropdownValue != null && Request.IsAjaxRequest() == true)
{
paymentApplicationRefund =
cPaymentRepository.PayableEntity(dropdownValue);
paymentApplicationRefund.Address1.Trim();
paymentApplicationRefund.Address2.Trim();
paymentApplicationRefund.Name.Trim();
paymentApplicationRefund.City.Trim();
paymentApplicationRefund.Contact.Trim();
paymentApplicationRefund.State.Trim();
paymentApplicationRefund.Zip.Trim();
return Json(paymentApplicationRefund,"application/json");
}
else
{
return null;
}
}
View 3 Replies
Nov 18, 2010
I am working on an ASP.NET application (well supposed to be deploying it about 3 days ago) and my hidden fields are loosing value when the form gets posted back..
I am using them to store information i write using javascript and on my own machine this works fine but as soon as i deploy it on our server everything else works except these values are lost..
I am using the .NET AJAX control toolkit on the same page and have noticed my calander datepicker also looses the data..
I have checked using firebug and the data is definitely getting post to the server but is getting lost somewhere!
View 1 Replies
Feb 25, 2016
can we store datatable into hiddenfield.
View 1 Replies
Dec 3, 2010
I can't get this to work:
I have a grid view with several TemplateFields. A couple of them are set to Visible=False; each template field has an EditItemTemplate, an ItemTemplate and a FooterTemplate.
[Code]....
While in GridView_RowUpdating event, the value bounded to the EditItemTemplate is properly read
[Code]....
so, debugging ttbImp.Text = "4"; But when trying to get the value bounded to the FooterTemplate, the label contains no values.
[Code]....
so, while debugging, lblImp.Text = "";
why that? I believe it has to do with the hidden visibility of the field, but I can't understand why it reads the value inEditItemTemplate, and it doesn't in FooterTemplate.
View 6 Replies
May 7, 2015
I have a hidden value field on a page. On submit I post to a different page. On the page I've posted to I do a Request.Form but I do not get the value just a null value. This is the initial page
<div id="booking_content_wrapper">
<form id="mainForm" name="mainForm" runat="server" action="Cancellation.aspx">
<h2>
Paid Bookings</h2>
<table cellpadding="0" cellspacing="0" border="0" id="booking_table">
<tr>
[code].....
The javascript ViewCancellation function is set to a hyperlink in the code behind. The function will have a value like this,<a href="#" onclick=" View Cancellation(54666);return false;">cancel</a>.
string sResID = "";
protected void Page_Load(object sender, EventArgs e) {
HttpContext context = HttpContext.Current;
sResID = context.Request.Form["ResID"] != null ? context.Request.Form["ResID"] : "";
sResID = Regex.Replace(sResID, "/[^A-Z]d-/g", "");
context.Response.Write(sResID);
}
View 1 Replies
Apr 15, 2010
I've got a gridview with a hidden field, i'm trying to set a value as follows:
value='<%# DataBinder.Eval(Container.DataItem, "Name")%>'
which works in most cases except when the name has an apostrophe like O'Neil. I need to escape the ' if possible.
so i tried: value='<%# DataBinder.Eval(Container.DataItem, "Name").ToString().Replace("'", " /' ")%>' and
value='<%# DataBinder.Eval(Container.DataItem, "Name").ToString().Replace("'", " //' ")%>'
which doesn't work because of the final apostrophe in the notation i.e. %>' It truncates after the word e.g O'Neil Someone becomes O' which is incorrect.
This works like a charm: value='<%# DataBinder.Eval(Container.DataItem, "Name").ToString().Replace("'", "'")%>' which isn't good practice as I don't want to hardcode '
View 3 Replies
Oct 3, 2013
My gridview has id in first column but I have hidden it . How do I send the gridview id to next page in query string.
View 1 Replies
Jan 9, 2011
I want to pass more than 10 text field data to another url.. How do i pass it securely
View 4 Replies
Oct 13, 2010
I have a ListBox on my page. I'm making an AJAX call to a C# function, and I need to pass the values of the selected items. Here's what I have:
$('#btnSubmit').click(function() {
$.ajax({
type: "POST",
url: 'Default.aspx/GetSelectedValues',
data: '{selectedValues: ' + $('#lbItems').serialize() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
});
<select id="lbItems" multiple="multiple">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
[System.Web.Services.WebMethod]
public static string GetSelectedValues(string selectedValues)
{
//
}
The data being passed to the C# function looks like:
lbItems=1&lbItems=3&lbItems=5
Is there any built-in C# function that can deserialize that easily, to convert the values into an array of some sort? Or maybe there's a better way to pass the data from jQuery?
View 3 Replies
Jun 1, 2010
I'm trying to pass JSON from jQuery to a .ASHX file. Example of the jQuery below:
$.ajax({
type: "POST",
url: "/test.ashx",
data: "{'file':'dave', 'type':'ward'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
How do I retrieve the JSON data in my .ASHX file? I have the method:
public void ProcessRequest(HttpContext context)
but I can't find the JSON values in the request.
View 5 Replies
Mar 7, 2011
I have the following javascript. Problem is if I enter one row in the table "ingredients" but I am getting 2 rows in the resulting pass to controller action after seralising into my C# object. But the second object is null? I checked the javascript and the variable "cnt" is 1 not 2. Why would that be?
[code]
$("#Save").click(function () {
var title = $("#recipetitle").val();
var category = $("#category").val();
var preptime = $("#prepTime").val();
var preptimeperiod = $("#lstPrepTime").val();
var cooktime = $("#cookTime").val();
var cooktimeperiod = $("#lstCookTime").val();
var rating = $("#rating").val();
var method = $("#method").val();
var jsontext = '{ "RecipeTitle": "' + title + '",';
jsontext += '"CategoryID":' + category + ',';
jsontext += '"PrepTime":' + preptime + ',';
jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",';
jsontext += '"CookTime":' + cooktime + ',';
jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",';
jsontext += '"Rating":' + rating + ',';
jsontext += '"Method":"' + method + '",';....................
View 1 Replies
Mar 9, 2010
I have an containing a list of divs that jQuery turns into progress bars. On .ready, I build a list of all of these progress bars and for each one, call a webservice that gets a value indicating how full the progress bar should be. In order to do this, I need to pass the ID of the div to the web service.
Because the divs are inside a ListView, I manually set the id to be id="completionbar_<%# Eval("MilestoneID") %>"
However, when I pass this id into my web service, it comes up as "undefined" every time. When I view the source, it looks like it's set correctly.
Here's the jQuery that calls my web service:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".MilestoneCompletion").progressbar({ value: 0 });
$.each($(".MilestoneCompletion"), function(index, barDiv) {
[Code].....
I'm thinking maybe the script is executing before the DIV id is set by the ListView databind?
View 2 Replies
May 12, 2010
the thing is that I have a form with a textbox and a button and a hidden field, now what i want to do is to write something in the textbox ,pass it to the hidden field and then access that thing written in the hidden field in the controller . how can i do that?
View 3 Replies
Jan 23, 2011
What is the difference when using ::
Hidden field vs View state??
when to use each one ??
which one more secure?? and which is better than in performance?
what are the alternatives?
View 3 Replies
Jun 4, 2010
I'm trying to create a JSON object on client-side and pass to a server-side function. Then instantiate it on server-side using JSON string representation.
So I create jSON object on client-side
var myJsonObject = {
"arg1": var1,
"arg2": var2
}
and pass it in to
WebForm_DoCallback(controlID, myJsonObject , null, null, null, true);
When I try to retrieve this JSON object on server-size I get as a string representation of JSON [object Object]
So in following server-side function, the argument value is [object Object]
public void RaiseCallbackEvent(string jsonObj)
I was expecting a string representation of JSON object. How do I pass in a string representation?
View 1 Replies
Jan 13, 2010
I have an ASP.NET PageMethod with the following signature:
<WebMethod()> _ Public Shared Function SaveCodes(ByVal codes As List(Of Code)) As String
I am trying to pass a JSON object to the PageMethod from the client side, but I get an error that the type String cannot be converted to type of List<Code>.
Here is the json that I'm building on the client and sending to the method:
[code]....
I have been able to pass in simple data types and a single instance of the Code class, but I can't seem to find the magin to pass a List to the server method. Can anyone show me what I'm doing wrong?
View 1 Replies
Nov 1, 2010
I am trying to send json data from view to controller action. But the issue is the data is not populating in the action parameter List<Score>.
View Model:
public class Score
{
public int QuestionId { get; set; }
public int PrevAnswerId { get; set; }
public int CurrAnswerId { get; set; }
public string CurrAnswerName { get; set; }
}
Json Data look like:
[
{QuestionId:1, PrevAnswerId:3, CurrAnswerId:3, CurrAnswerName:'Known to Broker'},
{QuestionId:2, PrevAnswerId:7, CurrAnswerId:7, CurrAnswerName:'Completed'},
{QuestionId:3, PrevAnswerId:10, CurrAnswerId:10, CurrAnswerName:'Report'}
]
On window load, I will construct the Json object using "eval()" function and do some operation in the data before its save. On Save Click, I will call the action through the ajax call.
$.ajax({
url: url,
type: "GET",
dataType: 'json',
data: {score: ScoreJson},
contentType: "application/json; charset=utf-8",
success: function () {
alert("succes");
},
error: function () {
alert("error...");
} });
Action:
public ActionResult SaveScore(List<Score> score)
{
// do something...
}
But here score comming as collection of 3 elements with zero(for interger property)/null(for string property) values. When I checked in the request I found the data in "parama" property like.
"Score%5b0%5d%5bQuestionId%5d=1 &Score%5b0%5d%5bPrevAnswerId%5d=3 &Score%5b0%5d%5bCurrAnswerId%5d=3 &Score%5b0%5d%5bCurrAnswerName%5d=Known+to+broker&
Score%5b1%5d%5bQuestionId%5d=2 &Score%5b1%5d%5bPrevAnswerId%5d=7 &Score%5b1%5d%5bCurrAnswerId%5d=7 &Score%5b1%5d%5bCurrAnswerName%5d=Completed&
Score%5b2%5d%5bQuestionId%5d=3 &Score%5b2%5d%5bPrevAnswerId%5d=10 &Score%5b2%5d%5bCurrAnswerId%5d=10 &Score%5b2%5d%5bCurrAnswerName%5d=Travelers+Report&".
But I am not sure why it is not getting populated in the score list. One full day I spent for this issue but till now I didnt find the solution for this issue.
View 4 Replies