loosing hidden field value after ajax call to c# code - c#

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

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.

How can I update the Database on a checkbox change in MVC

I am trying to update my database when a checkbox is checked or unchecked. I want it to update when the checkbox is clicked. This is what I have so far, but my controller is never being hit. what can I do to fix it? Ideally I want to pass in the new value of customer.IsDone and customer.Id to my controller but I don't know how to do this.
Checkbox in my view
<td>#Html.CheckBoxFor(m => customer.IsDone, new { onclick = "UpdateCustomer(IsDone)" })</td>
The function in my view
function UpdateCustomer(isDone) {
$.ajax({
type: 'POST',
url: #Url.Action("UpdateCustomer", "Home"),
data: { check: isDone },
success: success,
dataType: 'json'
});
}
this is my controller method
[HttpPost]
public ActionResult UpdateCustomer(bool check)
{
//code will be here to update the db
var customers = new CustomerGetAll();
var list = customers.Execute();
return View("Customers", list);
}
I see few issues in your code.
First of all, you are passing IsDone variable when calling the UpdateCustomer method. But where is isDone defined ?
Second, this line,
url: #Url.Action("UpdateCustomer", "Home"),
The Url.Action helper will output a string and your code will be like this when rendered in the browser
url: /Home/UpdateCustomer,
Now the browser's javascript framework usually thinks the second part after : as a js variable and if you have not defined it,it will throw a syntax error about using a not defined variable! But since we have \, you will get another "Invalid regular expression flags" syntax error!
You should wrap the result in quotes to avoid this problem.
The below code should work
#Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)" })
and the script
function UpdateCustomer(elem) {
var isDone = $(elem).is(':checked');
$.ajax({
type: 'POST',
url: "#Url.Action("UpdateCustomer", "Home")",
data: { check: isDone },
success: function(res) {
console.log(res);
},
dataType: 'json'
});
}
Also, If you want to update a specific customer record, you probably want to pass the customer Id as well when making the ajax call. You may keep that in html 5 data attribute on the checkbox markup and read that and use that as needed.
#Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)",
data_customerid = customer.Id })
This will render the checkbox with html5 data attribute for "data-customerid". All you have to now do is, read this value and send it via ajax
function UpdateCustomer(elem) {
var isDone = $(elem).is(':checked');
var cid = $(elem).data('customerid');
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateCustomer", "Home")',
data: { check: isDone,customerId:cid },
success: function(res) {
console.log(res);
}
});
}
Make sure your server action method has a new parameter to accept the customer id we are sending from client side code
[HttpPost]
public ActionResult UpdateCustomer(bool check,int customerId)
{
// to do : Save and return something
}
I have something similar, and I think you can solve your problem...
My HTML
<td>
#{
bool avalia1 = false;
#Html.CheckBox("avalia1", avalia1, new { autocomplete = "off", data_on_text = "Sim", data_off_text = "Não" })
}
</td>
JS
var avalia1 = $("#avalia1").is(":checked");
var url = "/Telefonia/GravarAvaliacao";
$.ajax({
url: url,
datatype: "json",
data: { 'avalia1': avalia1,'idgravacao': idgravacao },
type: "POST",
success: function (data) {
}
});
}
ON CONTROLLER
public JsonResult GravarAvaliacao(bool avalia1, string idgravacao)
{
string _userId = User.Identity.GetUserId();
var avaliaData = new OperadorAvaliacaoData();
avaliaData.GravaAvaliacao(avalia1, idgravacao);
return Json(true, JsonRequestBehavior.AllowGet);
}
The only diference is your model checkbox, and the action trigger.

How to get values inside object got through Json

I am using .NET MVC4
I have used javascript function as below:
function ShowDomainComponentDetail(compCode) {
alert(compCode);
$.ajax({
url: "/PP/getDomainComponentDetailWithDomain",
data: {
'ComponentCode': compCode
},
dataType: "json",
type: 'POST',
cache: false,
success: function (_responseData) {
$('#divShowDomainCompDetail').show();
alert(_responseData.Data)
},
error: function () {
//
}
});
}
Upon success I am getting list in .net as:
IdObservation=1, ObservationName="Started" , ObsType="Announced";
IdObservation=2, ObservationName="Not Started" , ObsType="Un Announced";
IdObservation=3, ObservationName="Declared" , ObsType="Announced";
My problem is i am not abl;e to access this list inside Ajax sucess block.
How can i access this list as:
alert(_responseData.IdObservation);
alert(_responseData.ObservationName);
(Further i am going to assign this to labels).
Please help me.
EDIT 1 :
My Serverside Function returning list:
public JsonResult getDomainComponentDetailWithDomain(string ComponentCode)
{
try
{
List<TEAMS_PP.Entity.correlations> compDetail_list = new correlation().getDomainComponentDetailswithDomain(ComponentCode);
return Json(compDetail_list);
}
catch (Exception)
{
List<TEAMS_PP.Entity.correlations> BlankList = new List<TEAMS_PP.Entity.correlations>();
return Json(BlankList);
}
}
Use index with data object like below:
alert(_responseData[0].IdObservation);
loop through object and get values for each object.
you can use the $each to iterate it
$.each(_responseData, function (key, value) {
var arr = value.IdObservation;
});

jQuery Get() to WebMethod not working

I'm trying to call the jQuery function $.get() to make a call to my WebMethod but it's only hitting the Page_Load event in the code behind. I can see the request being sent out in firebug to /admin/manage-users.aspx/deleteUser?u=user1 but it never hits the WebMethod.
jquery
$('#delete').each(function () {
$(this).click(function () {
var userName = $(this).closest('tr').find('span.userName').text();
$.get('/admin/manage-users.aspx/deleteUser', { u: userName });
});
});
aspx.cs
[WebMethod]
public void deleteUser() {
string userName = Request.QueryString["u"];
if(!string.IsNullOrEmpty(userName)) {
if(Membership.DeleteUser(userName))
Response.Redirect(Request.Url.ToString());
}
}
SOLUTION
I gave credit to bugz below because he pointed me in the right direction.
In order for your [WebMethod] to work your method within the aspx has to be static
Here is a link for more information
More Information
$.ajax({
type: "POST",
url: "'/admin/manage-users.aspx/deleteUser'",
data: "{'userName ' : '" + userName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//do something on success
},
error: function(ex) {
//do something on failure
}
});
Also on success if you are returning data or a variable make sure you use data.d for some reason when using jquery/ajax microsoft wants the .d at the end of the variable. This took me time to figure out.
Try this Im guessing when you debug the deleteUser Method never gets called.
var jqxhr = $.get("admin/manage-users.aspx/deleteUser", { userName: userName } function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

jquery AJAX sent data in key value pair

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

Categories