I am not sure what my problem is because when i click the button no error in console and the javascript is not triggered.
asp
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick='<%# "show("+Eval("I") +");" %>' />
server side
public partial class _Default : Page
{
public string ClientID = "1";
public string I = "2";
public string J = "3";
protected void Page_Load(object sender, EventArgs e)
{
//Page.DataBind();
}
}
javascript
function show(str) {
//var str = "test";
console.log(str);
event.preventDefault();
alert(str);
}
I've been referring to below post, but I still couldnt figure it out... will someone help?
How to pass bind or eval arguments with the client function "OnClientClicking"
Related
Trying to use public properties from C# code behind and want to read the variable value from a JavaScript function
JavaScript function:
function IsAgentInProgram()
{
var optStatus = "<%=AgentOptInStatus%>";
if (optStatus == "True")
alert("You are opted in!");
else
alert ("You are opted OUT");
}
C# code behind
public bool AgentOptInStatus;
private void Page_Load(object sender, System.EventArgs e)
{
this.AgentOptInStatus = true;
}
This does not work. Output comes back as You are opted OUT. I also did an alert on optStatus and it comes back with: "<%=AgentOptInStatus%>"
Am I missing something?
You cannot read the client side variables directly in the codebehind. What you can do is creating a hidden field and setting the value with javascript, then you can read it in c#.
<asp:HiddenField ID="hdnfldVariable" runat="server" />
JS:
<script type="text/javascript">
var somefunction = function () {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = 'value from javascript';
}
</script>
c# :
string selected = hdnfldVariable.Value.ToString();
Another option is to make an HTTP request to the server to call a function from a controller passing the data as parameters.
I have html button which calls a function in code behind and it fires only once.
I want it to fire event every time I click the button.
It is possibly duplicated but I have tried to add "!IsPostBack" but it doesn't work.
My ascx class:
<button runat="server" type="button" class="btn btn-report" onserverclick="OnReportBtnClick" id="reportBtn">
<i class="glyphicon glyphicon-floppy-disk"></i>
</button>
I have to use html button, not <asp:Button> because <asp:Button> doesn't let me to insert <i> tag inside.
Here is my code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
try
{
reportBtn.ServerClick += OnReportBtnClick;
}
catch (Exception ex)
{
}
}
}
//this method is called only once even I click the button many times afterwards.
protected void OnReportBtnClick(object sender, EventArgs e)
{
try
{
// Set file name
string pdfName = SPContext.Current.Web.Title + fileType;
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime startDate = DateTime.MinValue;
if (!string.IsNullOrEmpty(report_startDate_datePicker.Value))
startDate = DateTime.ParseExact(report_startDate_datePicker.Value, format, provider);
DateTime endDate = DateTime.MaxValue;
if (!string.IsNullOrEmpty(report_endDate_datePicker.Value))
endDate = DateTime.ParseExact(report_endDate_datePicker.Value, format, provider);
// Provisioning data for report
var report = GetReport(startDate, endDate);
// Merger data to template html
byte[] data = GetPdfData(htmlTemplate, report);
//Respond report to client
RenderResponse(pdfName, data);
}
catch (Exception ex)
{
LoggingService.LogError(LoggingService.NTT_ERROR,
string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
}
}
//I think the problem could be this method.
//I return a pdf file to client
private void RenderResponse(string pdfName, byte[] data)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + pdfName);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.BinaryWrite(data);
HttpContext.Current.Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
LoggingService.LogError(LoggingService.NTT_ERROR,
string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
}
You can use a LinkButton
<asp:LinkButton runat="server" ID="ReportBtn" Text="<i class='glyphicon glyphicon-floppy-disk'></i>" OnClick="ReportBtn_Click" CssClass="btn btn-report" />
in .cs page
protected void ReportBtn_Click(object sender, EventArgs e)
{
//your code
}
They do support html in the text field.
I saw on stackoverflow we can do this to populate js variables with ViewBags (with razor):
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var userInfoJson = jss.Serialize(ViewBag.User);
}
with this:
<script>
//use Json.parse to convert string to Json
var userInfo = JSON.parse('#Html.Raw(userInfoJson)');
</script>
I want to do the same thing with aspx not razor. Can you help me?
In my controller:
Viewbag.test="Thanks to you it works!"
In my aspx:
public String test {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
test = ViewBag.test;
}
<script>
alert('<%=test%>');
</script>
Result: Thanks to you it works!
Add a public property to your page and populate it on Page Load (you may have to do it on Page Init, I can't remember which processes first).
public UserType UserToSerialize {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
UserToSerialize = LoadUser(); //I assume you've got some magic to do this already
}
Markup:
<script>
var userInfo = JSON.parse("<%# new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(UserToSerialize) %>");
</script>
Notice I use UserToSerialize to avoid interfering with the Page.User property.
I am using Following code..
When I click on the link, the javascript Hello() function is invoked
I want to use window.location.href
But when I use this the following __doPostBack('Button2_Click'), it does not work.
But when remove window.location.href from the following code then __doPostBack('Button2_Click') does work.
<script type="text/javascript">
function Hello(clicked_id) {
var abc = "http://localhost:2621/OrgChart.aspx?id" + clicked_id;
window.location.href = abc;
__doPostBack('Button2_Click');
return false;
}
</script>
<a id="A1" href="javascript:Hello();">LINK</a>
This is my code behind code...
public partial class WebForm17 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(this, string.Empty);//This is important to make the "__doPostBack()" method, works properly
if (Request.Form["__EVENTTARGET"] == "Button2_Click")
{
//call the method
Button2_Click(this, new EventArgs());
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "Method called!!!";
EmpInfo emp = new EmpInfo();
DA_EmpInfo da_emp = new DA_EmpInfo();
List<EmpInfo> lei = da_emp.GetAllEmployeeInfoByEmpId("MJ-IB-1");
DetailsView1.DataSource = lei;
DetailsView1.DataBind();
}
}
I guess, __doPostBack is making a request to the server and you break it by using window.location.href = abc;.
You should use some callback from this request to redirect to your url.
try to use setTimeOut function
setTimeout(function () {
window.location.href = abc;
}, 1000);
this will wait 1 second for finish of __doPostBack() function.
Or if you don't want to use timeOut, paste window.location.href = abc; line to end of the __doPostBack() function.
On the click of a button, I call a JavaScript function. After getting the value, I need to perform some stuff from the value obtained in the code-behind. How should I call code-behind?
My aspx:
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
//After this I need to perform stuff 'Upload(TxtInput.value)' into database from the code-behind
}
The button calling the function is set up in the following manner:
<button class="doActionButton" id="btnSelectImage" runat="server" onclick="openWindow('../rcwksheet/popups/uploader.htm')">Select Image</button>
My desired code behind (VB):
Public Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectImage.ServerClick
Dim inputFile As String = Me.TxtInput.Value
//do more stuff here
End Sub
So:
Is there a way to call code-behind from the JavaScript?
Can I somehow use the "onclick" property of a button to first go to a JavaScript and then to the code-behind?
Trigger a code-behind call "onchange" of the TxtInput.Value?
yes there is a way.
first, you can use javascript to submit the form after your return value is set in TxtInput.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
document.forms[0].submit();
}
then in your code behind, you can handle TxtInput's value in page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (this.Input.Value != string.Empty)
{
this.Input.Value += "blah";
}
}
}
note: you may need Identifying control that caused postback
You can put the server side code into a web service, make a service reference in an asp:ScriptManager on your aspx page and then you can call/execute the web service from javascript by calling:
WebServiceClassName.MethodName(javascriptvariable, doSomethingOnSuccess)
Here is a link on doing that:
http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
You can call the __doPostBack Event.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
__doPostBack('btnSelectImage', getval);
}
And on the server side in your code behind, you can get the value:
In the PageLoad method:
if (Request.Form["__EVENTTARGET"] == "btnSelectImage")
{
//get the argument passed
string parameter = Request["__EVENTARGUMENT"];
//fire event
btnSaveImage_Click(this, new EventArgs());
}