how can i prevent code behind method call in asp.net - c#

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();
}

Related

Invalid postback or callback argument - Button OnClick

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.

Need to go Javascript Method before hit the MVC controller method

I have MVC project. I need to do client side validation on run time. When click the form submit button I need to hit JavaScript Method first and then it is return true move to Controller method.
Just Assume following code type:
JavaScript OnClick Method:
$(function () {
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
event.preventDefault();
alert(data);
return false;
}
else {
return true;
}
}
});
});
});
Controller Method:
[HttpPost]
[BaseAuthenticationFilter(UserTypeEnum.Admin, PermissionEnum.CanSendRemittance)]
public ActionResult Create(Invoice model)
{
// Method Goes here
}
Here I cant popup validation alert message. When I click the button it will hit the Controller method. I need to go first javascript method and then if true go to controller method
Please help this.
Try following code, you have to return false in click handler directly instead of ajax response event. because ajax is asynchronous it will execute the ajax and call out from event handler immediately before getting the response of ajax.
So check if data not exists then submit the form otherwise show validation message
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
alert(data);
}
else {
$("form").submit();
}
}
});
event.preventDefault();
return false;
});

How to use custom AuthorizeAttribute with AJAX

With help of fellow friends I managed to find a solution for my problem from this topic: Reusable way to allow an account to be used by a single person at a time
I have a SingleLogin class which inherits from AuthorizeAttribute and implements a custom AuthorizeCore method for the purpose of re-usability of my single-login code:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
int userId = (int)WebSecurity.CurrentUserId;
using (var db = new UsersContext())
{
if ((httpContext.Session.SessionID != db.getSessionId(userId))
|| db.getSessionId(userId) == null)
{
WebSecurity.Logout();
isAuthorized = false;
httpContext.Response.Redirect("/Home/Index");
}
}
}
return isAuthorized;
}
Everything works fine except my JsonResult action:
[HttpPost]
public JsonResult MessageSave(string message)
{
bool messageSaved = false;
int userId = (int)WebSecurity.CurrentUserId;
message = HttpUtility.HtmlEncode(message);
// Model method - adding chat log - db
db.addChatLog(message, userId);
messageSaved = true;
return Json(new { messageSaved = messageSaved });
}
This method is triggered by Ajax POST call which you can see in code example below. Just basic POST.
EDIT 3
Please check these images: http://imgur.com/a/Cjael .. Hm I guess POST does trigger, but have no idea why does my alert not work when I try to test it before $.ajax ... As you can see in response I do get Home/Index page but I am not redirected to home/index immediately(text stays inside of textBox and page just waits..), I have to push enter one more time to be redirected.. Very strange.
EDIT2
Seems like I can't even access my jQuery even after I get logged out. I put some alerts inside of my .js file.
I have a separate .js file which is then put in my View as <script src="~/Scripts/custom/homeChat.js"></script> . I pass the Razor values from View into my JS file via HTML5 data-.
My textBox element #txtMsg, triggers my jQuery event, therefore when I am logged out it probably doesn't recognize my textBox element anymore, and doesn't trigger my jQuery event?
Element that triggers .js in view is:
#Html.TextBox("txtMsg")
JS:
$("#txtMsg").keypress(function (e) {
//when enter
if (e.which == 13) {
alert("ALERT DOESNT TRIGGER");
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ message: input }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.messageSaved) {
$("#txtMsg").val("");
}
else {
window.location.href = urlhome;
}
}
});
}
}
});
So if you can't even come into your event, how can you even know something went wrong? I have this ˙HandleUnauthorizedRequest but you are required that you can get into your jQuery event(in my case .keypress in the js code above) for this to work if I understand right.
EDIT: Additional explanation
So let me explain the scenario. If I login with my username "john" from Firefox and again with username "john" from chrome, next action I do in Firefox, it will log me out and redirect me to Home/Index, because someone else made a new login in Chrome.
That is ok. Since you are not logged in anymore, you get redirected normally to your Home/Index if your action is normal ActionResult and returns view.
The problem I have is, that I have some other functionality in the page, which uses Ajax POST, and since you are logged out you can't POST to that JsonResult action therefore you can't even receive callback of error, which redirects you to Home/Index. I put some alerts into my JS, but no alert triggers which is normal, because I am not allowed on that page anymore anyway. If I want that my onEnter textbox redirects me to Home/Index I have to press enter twice. Is that all that could be done?
I am interested in best approach for this AJAX problem. I don't know how I should call it, but as I read from my previous topic it is called "handling AJAX timeouts"?
Thank you very much.
You can handle errors on AJAX request this way
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ message: input }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.messageSaved) {
$("#txtMsg").val("");
}
else {
window.location.href = urlhome;
}
},
error: function(xhr, status, error) {
// TODO: may be check error or status or xhr.statusCode()
window.location.href = urlhome;
}
});
jQuery $.ajax() docs
If understand it correctly you want to handle the unauthorized ajax request.
In that case you can override the HandleUnauthorizedRequest method in your attribute:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
filterContext.Result = new JsonResult();
}
else
{
filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.Forbidden);
}
}

loosing hidden field value after ajax call to c# code

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

update field or redirect page using jquery and asp.net mvc

Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.
click a submit button
this calls an action method called LogOn in the controller Account
if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)
if it fails replace a div(with id="error") with "sorry error occured"
so far I tried this:
$("#submit")
.button()
.click(function () {
$.ajax({
type: "POST",
url: "Account/LogOn",
dataType: "json",
success: function (data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error2").replaceWith(data.error);
}
}
});
});
how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.
Thanks
If you want to redirect asp.net page at same directory , you can by Jquery/Java script by this :
$("#ctl00_iframecontent_BtnCancle").click(function () {
window.location = "IncSLAList.aspx?bi=37";
});
and
To redirect to Another page of project , can use :
window.location.href = "http://ImageUpload/Welcome.aspx?
Your jQuery is almost correct:
Don't call .button() (unless you're using jQuery UI and want to do that)
Add return false; at the end of the click handler to prevent the browser from submitting normally.
In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).

Categories