I have a WebMethod that updates an SQL database based on parameters passed from a ASP.NET button. On success the WebMethod returns the state and is used to show or hide a div. However the Javascript condition always evaluates as "Yes" even though "No" is passed back.
Control:
<telerik:RadButton
TabIndex="1"
ID="Updated"
runat="server"
ButtonType="ToggleButton"
ToggleType="Checkbox"
AutoPostBack="false"
OnClientToggleStateChanged="ButtonSelect"
CommandArgument="Updated"
CommandName="Updated">
<ToggleStates>
<telerik:RadButtonToggleState
Text="No"
PrimaryIconCssClass="rbToggleRadio">
</telerik:RadButtonToggleState>
<telerik:RadButtonToggleState
Text="Yes"
PrimaryIconCssClass="rbToggleRadioChecked">
</telerik:RadButtonToggleState>
</ToggleStates>
</telerik:RadButton>
JQuery:
<script type="text/javascript">
function ButtonSelect(button, args) {
var state = args.get_currentToggleState().get_text();
var whois = args.get_commandName();
PageMethods.ButtonWebMethod(state, whois, onSucess, onError);
//edited Stack Overflow Quetion here to == from =:
function onSucess(returnstate) {
if ((whois == "Updated") && (returnState == "Yes"))
{
$("#updateChoiceDIV").show();
alert(returnstate + "Yep");
}
else if ((whois == "Updated") && (returnState == "No"))
{
$("#updateChoiceDIV").hide();
alert(returnstate + "Nope");
}
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
</script>
WebMethod:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string ButtonWebMethod(string state, string whois)
{
string returnState = state;
HttpContext.Current.Session["FieldName"] = whois;
if (state == "Yes")
{
HttpContext.Current.Session["" + whois + ""] = "True";
}
else if (state == "No")
{
HttpContext.Current.Session["" + whois + ""] = "False";
}
string strConnString = WebConfigurationManager.
ConnectionStrings["gatorConnectionString"].
ConnectionString;
try
{
string sql = "UPDATE [User] SET " +
HttpContext.Current.Session["FieldName"] + "='" +
HttpContext.Current.Session["" + whois + ""] +
"' WHERE Id = '" + HttpContext.Current.Session["newID"] +
"' ";
using (SqlConnection conn = new SqlConnection(strConnString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
catch (SqlException ex)
{
string msg = "Update Error:";
msg += ex.Message;
}
return returnState;
}
And yes I'm not great at Javascript so be kind....
=
is assignment which will always be true.==
and===
is equality. You have typos in your expressions.console.log(literal|variable|expression)
in your logic at pretty much any point to see in the console what is going on. Ex.console.log(returnState); console.log(returnState == "Yes");
returnstate
but checkingreturnState
. Case is sensative on variables.