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.
Related
So having a bit trouble figuring out how to successfully use AJAX to call a method and retrieve data. I am being asked to do this, not exactly sure why but I would usually just handle all this stuff in a MVC environment in the Controller. But for now I am asked to do this in AJAX. I have a ASPX file that I am simply trying to see work so i can move on. So far none of the stack overflow suggestions helped.
Here's what I currently have:
.ASPX/source
<script type="text/javascript">
$(document).ready(function () {
$("#go").click(function () {
$.ajax({
type: "GET",
url: "Default.aspx/ItemData",
processData: true,
data: {},
dataType: "json",
success: function () { alert("yay") },
error: function () { alert("nay") }
});
});
});
</script>
And then in my Default.aspx.cs file I have a method 'ItemData'
[WebMethod]
public static NextCrew.Models.Item ItemData(string cookieID)
{
Item item = new Item();
item.name = "Fred";
item.idx = 1;
item.completed = 1;
return item;
}
(Item is simple a Model withg 3 properties: Name(string), idx(int) and completed(int) )
I am having a hard time figuring out what I am doing wrong here. Can someone please write an example of what I am trying to do? Just a simple GET request that I can return an object (once I get done testing I want to be able to connect to a DB so I need it to be an object) using AJAX.
I can't tell what I am doing wrong but I have some ideas:
1)maybe my url in the ajax isn't formatted properly?
2)do i need to pass anything into data if I have a parameter?
3)is my get method in the correct .cs file?
UPDATE
I was informed I need to have a special class to handle this. I tried to then make a .asmx and the AJAX is still not being called. Hoping someone sees an error that I missed.
<script>
$(function () {
$.ajax({
type: "POST",
contentType: "application/json",
url: "WebService2.asmx/GetItems",
data: "{}",
dataType: 'Json',
success: function (result) {
// alert(result.d);
$.each(result.d, function (index, ele) {
$("#Myddl").append("<option value='" + ele.value + "'>" + ele.text + "</option>");
})
}
});
})
</script>
.asmx
public class WebService2 : System.Web.Services.WebService
{
[WebMethod]
public List<Item2> GetItems()
{
//suppose data comes from database
var result = new List<Item2>() {
new Item2{ text="one",value="one"},
new Item2{ text="two",value="two"},
new Item2{ text="three",value="three"}
};
return result;
}
public class Item2
{
public string text { get; set; }
public string value { get; set; }
}
}
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!
I am creating registration page and doing null field validation on submit button click using jquery. if there is any error in form validation then i am preventing default method call using jquery, so it will not call code behind button click event.
Problem:
sometimes user double clicked on button and this is calling code behind button click event two times with two database row insertion having a same data.
I tried lots of solution but unfortunately i couldn't make any success.
Please help me to solve out this problem if you have any solution.
Thanks in advance,
Actually, i was preventing default server side method call in jquery when button is clicked using e.PreventDefault() method of jquery if validation is false.
Don't know what was the problem but when i set function on client click of button and return true/false based on validation instead of e.PreventDefault, trick worked great for me.
Thanks to all who comment on this question.
Simply add a variable called 'loading' for example and check if the ajax call is busy:
At the top of your code:
var loading = false;
Then on form submit:
$('#form').submit() {
if(loading)
return false;
loading = true;
//Ajax call
$.ajax({
type: "POST",
url: "somePage.php",
data: $('#form').serialize(),
success: function(response) {
loading = false;
//Your response code
}
});
}
Use one on the client side. This will prevent double clicks.
$("#button").one("click", function() {
// validate the form.
// if form is valid, submit form
});
An alternative solution is to have a boolean flag.
var submitting = false;
$("#button").click(function() {
if (!submitting) {
submitting = true;
if (formIsValid) {
submitting = false;
$("#form").submit();
} else {
submitting = false;
}
}
});
Add disabled attribute to your button as the first thing in your js method.
function func(event) {
$("#button").prop("disabled", true);
.....
}
try this it might help for your asp button
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" UseSubmitBehavior="false" OnClientClick="ValidationCode(event); return false;" />
<script>
function ValidationCode()
{
//Code of validtion
event.preventDefault();
if(true)
{
__dopostback:("btnSubmit","");
}
}
</script>
Sample code
Client Side:
$("#submit").click(function () {
if (!YourvalidationFunction)
{
return false;
}
else {
//ajax_function is a folder contain Default.asmx page and insertNewRecord is function name (server side)
$.ajax({
type: "POST",
url: "ajax_function/Default.asmx/insertNewRecord",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessinsertingwcCall,
error: OnErrorCall
});
}
});
Server Side:
[WebMethod]
public string[] insertNewRecord(string prefix)
{
string status = "";
List<string> d = new List<string>();
try
{
// logic code for insertion if success set msg
status = "New record inserted";
}
catch (Exception ac)
{
status = " Error occurs";
}
d.Add(string.Format("{0}", status));
return d.ToArray();
}
Using jquery 1.7.2 and .net 4.0
I have a json ajax call that sets the value of a asp hidden field on my form. While stepping through the code behind I can see the value the hidden field is set but when the code returns to the aspx code the value is empty.
ASPX code:
<asp:HiddenField ID="hidden1" runat="server" />
//dropdownlist on change event calls the function below:
function getReport() {
var data = { MethodName: 'myMethod', value1: value1 }
var options = {
url: '<%=ResolveUrl("myPage.aspx") %>',
async: false,
data: data,
datatype: 'text',
type: 'POST',
success: function () {
var returnedData = $("#hidden1").val();
alert('returned data = ' + returnedData);
}
}
$.ajax(options);
//also tried alerting the returned data here.. still empty
}
c# code behind:
#region AJAX
if (Request.Form["MethodName"] == "myMethod")
{
hidden1.Value = "please just pass this value!!!";
return;
}
else
{
//do something different.
}
#endregion
I've simplified my code, hopefully not too much. and I double checked my code to make sure the hidden field value is not set elsewhere in the code.
Due to the ajax call the the hidden field will not be updated. You must use the data which is returned by the ajax call.
function getReport() {
var data = { MethodName: 'myMethod', value1: value1 }
var options = {
url: '<%=ResolveUrl("myPage.aspx") %>',
async: false,
data: data,
datatype: 'text',
type: 'POST',
success: function (returnedData) {
alert('returned data = ' + returnedData);
}
}
$.ajax(options);
}
code behind:
#region AJAX
if (Request.Form["MethodName"] == "myMethod")
{
return "please just pass this value!!!";
}
else
{
//do something different.
}
#endregion
I have one Radio buttonlist with two radio buttons and one dropdownlist in my asp.net web application. I need to change the drop down list values with respect to selecting radio buttons in client side using Ajax Cascading drop down. Can any one provide solutions for that means it will really helpful for my project.
Thank you...
I have a ready code for a similar requirement. i hope it helps.
Solution : Let's say there is a xml file with states. This is your data source for drop down list which you need to populate on radio button click.
<?xml version="1.0" encoding="utf-8" ?>
<states>
<state name="ALABAMA" abbreviation="AL" />
<state name="ALASKA" abbreviation="AK" />
</states>
Aspx code
<asp:RadioButtonList CssClass="radio" runat="server" ID="rblist">
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="2">No</asp:ListItem>
</asp:RadioButtonList>
<br/>
<asp:DropDownList runat="server" ID="ddlStates"/>
Jquery code to call a web method
<script type="text/javascript">
$(document).ready(function () {
$("input:radio[name='rblist']").click(function () {
var selectedRadio = $("input:radio[name='rblist']:checked").val();
//Code to fetch complex datatype
$.ajax({
type: "POST",
url: "/Samples.aspx/GetStatesWithAbbr",
dataType: "json",
data: "{ id :'" + selectedRadio + "'}",
contentType: "application/json; charset=utf-8",
success: function (msg) {
//alert(msg.d);
$("#ddlStates").get(0).options.length = 0;
$("#ddlStates").get(0).options[0] = new Option("-- Select state --", "-1");
$.each(msg.d, function (index, item) {
$("#ddlStates").get(0).options[$("#ddlStates").get(0).options.length] = new Option(item.Name, item.Abbreviation);
});
},
error: function () {
alert('error');
}
});
});
$("#ddlStates").bind("change", function () {
$('#' + '<%= lblSelectedState.ClientID %>').val($(this).val());
});
});
</script>
WebMethod in the same page code behind
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<State> GetStatesWithAbbr(string id)
{
List<State> sbStates = new List<State>();
XmlDocument doc = new XmlDocument();
string filePath = HttpContext.Current.Server.MapPath("~/App_Data/States.xml");
doc.Load(filePath);
try
{
foreach (XmlElement xnl in doc.DocumentElement.ChildNodes)
{
State st = new State();
st.Name = xnl.Attributes["name"].Value;
st.Abbreviation = xnl.Attributes["abbreviation"].Value;
st.value = xnl.Attributes["name"].Value;
sbStates.Add(st);
}
}
catch (Exception ex)
{
string exp = ex.ToString(); //Setup a breakpoint here to verify any exceptions raised.
}
return sbStates;
}
State Class
public class State
{
public string Name { get; set; }
public string value { get; set; }
public string Abbreviation { get; set; }
}
Explaination
1. On click of radio button we call a web method defined in code
behind.
2. web method accepts radio button's selected value and returns the states.
3. State is a complex type.Returned type is json.
4. On Success returned data is populated in dropdownlist.
I assumed that you are familiar with Jquery.