I am working on asp.net application. Where for a page I have to clear the value of the controls(like textbox and dropdownlist,etc), also i have to remove the value of a ViewState. Initailly i was doing it from codebehind, so o problem was there. But now the problem arise when i tried reset the value of controls using client side , say
document.getElementById('<%= txtTextBox.ClientID %>').value ='';
but the problem i am facing is that i cannot set the viewstate value from clientside.
my i have to clear to viewstate one is a simple variable say ViewState["NameOfUser"],and another one is converting a datatable into viewstate say,
ViewState["dataTable"] = dt;
Thanks and regards
You simply can not assign value in client side.
Either you have to pass it through hidden field while submitting form or
Call ajax from javascript and access the ViewState server side.
I found this way via ajax request:
Credits: https://forums.asp.net/t/1991868.aspx?Set+value+of+Viewstate+from+Javascript+or+Jquery
ViewState["dataTable"] = dt;
Javascript:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function () {
$("#Button1").click(function () {
//clear datatable
$.ajax({
type: "POST",
url: "WebForm1.aspx/ClearDataTable",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('cleared');
}
});
//clear other values.....
//............
});
})
</script>
On codebehind:
[WebMethod]
public static void ClearDataTable()
{
HttpContext.Current.Session["datatable"] = null;
}
Hope that it helps!
Related
I'm changing Jquery version from jquery-1.10.2 to jquery-3.6.3 but the method callings are not working due to this version change. My .NET Framework version is 4.7.2
I have used the new reference like below:
<script src="../Scripts/Version3.6.3/jquery-3.6.3.min.js?version=<%=ApplicationVersion.GetApplicationVersion()%>" type="text/javascript"></script>
calling client side JQuery POST method:
$.post("/employer/employerbrowse.aspx/SelectEmployer",
{ key: key },
function (data, textStatus, jqXHR) {
alert(data);
});
c# method:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false)]
public string SelectEmployer(string key)
{
string strUrl = "";
return strUrl;
}
After calling the "SelectEmployer" method it redirecting to page load only not in the desired page method.
Thanks in advance.
use AJAX to make the call to webMethod
$.ajax(
{
type: "POST",
url: "employerbrowse.asmx/SelectEmployer",
data: JSON.stringify({ key: _key}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
}
}
);
Further ... I notice your webmethod is in a normal aspx page, whenever ive tried that it hasnt worked and needed to add a Web Service (asmx) but you might be alright... Youd keep js/ajax call in aspx page if using this.
I have seen many posts about this error on an aspx web form page.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
My issue seems to be a little different. All of the posts I have read seem to be related to grid views, drop down lists, and other controls loading outside of Page_Load event.
In this case, I get this error with a simple Button click:
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Button1_Click just calls a simple method.
Now, in this Codebehind file, I do have 2 WebMethods that load a dropdown list from another drop down list value in jQuery Ajax. Could the fact that I have WebMethods exposed be the issue with the error?
All of the Click events on the page are now blocked.
Here is the jQuery and WebMethod code.
<script type="text/javascript">
$("#<%= ddlJobNumber.ClientID %>").change(function (e) {
var jobNumber = $(this).val();
FillPhaseCode(jobNumber);
SetDescription(jobNumber);
});
function FillPhaseCode(jobNumber)
{
$.ajax({
type: "POST",
<%--//url: '<% ResolveUrl("~/Pages/JobTimecard.aspx/FillPhaseCode"); %>',--%>
url: "JobTimecard.aspx/FillPhaseCode",
contentType: "application/json; charset=utf-8",
data: '{"jobNumber":"' + jobNumber + '"}',
dataType: "json",
success: function (result) {
$("#<%= ddlPhaseCode.ClientID %>").empty();
$.each(result.d, function (key, value) {
$("#<%= ddlPhaseCode.ClientID %>").append("option value='0'>Select</option>");
$("#<%= ddlPhaseCode.ClientID %>").append($("<option></option>").val(value.PhaseCode).html(value.PhaseDesc));
});
},
error: function ajaxError(result) {
alert("Error result: " + result.status);
}
});
}
function SetDescription(jobNumber)
{
$.ajax({
type: "POST",
url: "JobTimecard.aspx/SetJobDescription",
contentType: "application/json; charset=utf-8",
data: '{"jobNumber":"' + jobNumber + '"}',
dataType: "json",
success: function (result) {
$("#<%= lblJobName.ClientID %>").text(result.d);
},
error: function ajaxError(result) {
alert("Error result: " + result.status);
}
});
}
</script>
public class PhaseCodes
{
public string PhaseCode { get; set; }
public string PhaseDesc { get; set; }
}
[WebMethod]
public static List<PhaseCodes> FillPhaseCode(string jobNumber)
{
SpectrumSim clsSpectrum = new SpectrumSim();
DataTable dt = new DataTable();
dt = clsSpectrum.GetPhaseCodes(jobNumber, "1");
List<PhaseCodes> list = new List<PhaseCodes>();
foreach (DataRow dr in dt.Rows)
list.Add(new PhaseCodes
{
PhaseCode = dr["Phase_Code"].ToString(),
PhaseDesc = dr["Description"].ToString()
});
return list;
}
[WebMethod]
public static string SetJobDescription(string jobNumber)
{
DataTable dt = new DataTable();
SpectrumSim clsSpectrum = new SpectrumSim();
dt = clsSpectrum.GetJobNumbers();
var dataRow = dt.AsEnumerable().Where(x => x.Field<string>("Job_Number") == jobNumber).FirstOrDefault();
string description = dataRow["Job_Description"].ToString();
return description;
}
I hope it is that simple, but I can't find the issue.
EDIT:
here is my Page Load event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillJobNumberDropdown();
if (TimeId != 0)
{
LoadTimecard();
}
}
}
I'm guessing that on PostBack Web Forms is detecting a value in the server-side DropDownList that it doesn't recognise as a valid option because you are adding options to it client-side.
Does the DropDownList(s) that is being changed client-side need to be server-side controls?
If so, you will need to populate it with the same options on PostBack before Page_Load (eg. Page_Init) so it can recognise the selected option.
Alternately, change to a non-server-side HTML control instead and use Request.Form to get the selected value.
To solve this problem in a Web Forms scenario, I just ended up using an UpdatePanel to build the cascade dropdownlist.
The HTML control will work too, but I did not want a mix of controls.
I am calling a Web Method using Json and get HTML as a result.
I'm trying to set the value of a hidden field with this HTML and then access this hidden field from
server side but the hidden field value is always empty.
please help.
thanks
$.ajax({
type: "POST",
url: "ws/srv.asmx/GetReportResult",
data: JSON.stringify(prm),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status) {
var result = JSON.parse(data.d);
$("myHiddenField").val = result;
},
error: function (request, status, error) {
alert(request.statusText);
}
});
Try changing this line
$("myHiddenField").val = result;
To become
$("myHiddenField").val(result);
Jquery val is a function, so the parenthesis will fix the assignment.
are you have a hidden field control on server side? Than maybe your hidden field id is not myHiddenField when rendered to the page. Check your hidden field on browser and make sure its id is myHiddenField.
if it something like ct100_ct1242_myhiddenField than you can change
$("#myHiddenField").val = result;
with
$("[id$='myHiddenField']").val = result;
and if there is no codes changing the hidden field value on page load , page init etc you should see the result.
I have two asp.net dropdownlists that I want to manipulate clientside with Javascript.
These two dropdowns are inside a modal open: function()
When dropdown1.value == "me"
I want dropdown2.value to be disabled
How can I accomplish this?
$(document).ready(function () {
if (document.getElementById('<%=dropdown1.ClientID%>').value == 'Me')
document.getElementById('<%=dropdown2.ClientID%>').disabled = true;
});
(optional) Part 2 I need to set an entity framework value to null after dropdown2 has been disabled how could I accomplish this without a postback?
Part 1:
$(document).ready(function ()
{
if($("#<%=dropdown1.ClientID%>").val() == "Me")
$("#<%=dropdown2.ClientID%>").prop("disabled",true);
});
Part 2 :
You would need to make an ajax call to a code behind or webservice to do that.
.ASPX
$.ajax({
type: "POST",
url: "PageName.aspx/CodeBehindMethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
},
error: function (error) {
}
});
.ASPX.CS
[WebMethod]
public static void Test()
{
// Call EF code
}
In my aspx page, i have the js like this :-
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = "{'datakey':'hello'}"
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});
</script>
In the same webpage code behind class file ,i have the webmethod defined like this:-
[WebMethod]
public static string SendFile(string key, string data)
{
return data;
}
For some reason, i am able to get the data in the alert used on the html side. alert(msg); is giving me nothing and i am expecting to get the passed value back. In this case it should be 'Hello'.
I am missing something very small here, please help me out here.
Alter these.
The AJAX Call
$(document).ready(function () {
$("#btnLoad").click(function (evt) {
var dataForAjax = "{'datakey':'hello'}";
$.ajax({
contentType: "application/json",
data: dataForAjax,
type: "POST",
url: 'Test1.aspx/SendFile',
success: function (msg) {
var msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg.datakey);
}
});
evt.preventDefault();
});
});
The WebMethod
[WebMethod]
public static object SendFile(string datakey)
{
return new
{
datakey = datakey
};
}
Hope this helps.
Update:
`evt.preventDefault is for preventing postback in case your control was something like input type="submit" or asp:Button
.d is ASP.NET 3.5+ feature to prevent XSS vulnerability. ( link here )
The return type is object for the web method for automatic serialization ( link here )
Also you could omitdataType in $.ajax call but contentType is an absolute necessity ( link here )
This:
var dataForAjax = "{'datakey':'hello'}"
Should be:
var dataForAjax = {'datakey':'hello'}
AJAX does not (by default anyway) send json - it sends FORM INPUT elements! jQuery is nice and will convert javascript objects into that for you.
If you really need to you can send json, but I really doubt you do, it's rare to do that.
When you send data to method you must send apropriate key-value pairs, using object in Javascript.
Examle for you method:
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = {'key' :'datakey', 'data' : 'hello'};
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});