This is my front-end:
ImageButton Details = (ImageButton)e.Row.FindControl("iBtnDetails");//take lable id
String strApplication1 = Details.CommandArgument.ToString();
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes.Add("onClick", "SelectRow()");
This is my back-end:
<script type="text/javascript">
function SelectRow() {
var strApplication1 = '<%=strApplication1%>'
if (strApplication1 == "IT Application Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "IT Account Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Change Control Management")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Backup & Restore")
{
window.open('http://.aspx', '_blank');
}
}
</script>
I want to pass String Argument to javascript function, but I got error that strApplication1 doesn't exist in the current context.
You need to make strApplication1 a public property on your page class. Currently, it is just an internal variable.
Something like:
public partial class YourPage : System.Web.UI.Page
{
public string strApplication1 {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
//Your page logic
}
//Looks like you set the variable in an onDatabound or similar.
//So use this where you currently set the variable
strApplication1 = Details.CommandArgument.ToString();
}
Related
I am passing the value of doctype variable from my c# code to javascript.
Now I am unable to find any file based on the inputs.
Does the naming convention has to be exact?
Edit: Added current version with DocType hardcoded in onclick javascript page.
Variable:
DOC_TYPE in ascx.cs
DocType in ascx
AllGroup_UserControl.ascx.cs:
public partial class AllGroup_UserControl : UserControl
{
ProductProvider provider = new ProductProvider();
TBL_USER_PROFILEProvider uprovider = new TBL_USER_PROFILEProvider();
DocumentProvider dprovider = new DocumentProvider();
int DOC_TYPE;
// Document Types
const int G1_DOC_TYPE = 1;
const int G2_DOC_TYPE = 2;
const int G3_DOC_TYPE = 3;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userName = SPContext.Current.Web.CurrentUser.Name;
TBL_USER_PROFILE p = uprovider.GetUser(userName);
if (p != null)
{
List<string> G1List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 1");
List<string> G2List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 2");
List<string> G3List = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 3");
if (G1List.Count != 0)
{
DOC_TYPE = G1_DOC_TYPE;
}
else if (G2List.Count != 0)
{
DOC_TYPE = G2_DOC_TYPE;
}
else if (G3List.Count != 0)
{
DOC_TYPE = G3_DOC_TYPE;
}
else
{
Response.Redirect("/SitePages/AccessDeny.aspx");
}
Page.DataBind();
}
}
}
public int DocType
{
get
{
return DOC_TYPE;
}
}
//rest of the code
AllGroup_UserControl.ascx:
<a href="#" runat="server" onclick="openDialog('/SitePages/FileDownload.aspx?DocType=<%# DocType %>&ItemNo=<%#Eval("StoreItemNo")%>&CustomerID=<%#Eval("CustomerID")%>')">
ADDED:
Working code with docType hardcoded:
Group1_UserControl.ascx.cs: (with doctype hardcoded)
public partial class Group1_UserControl : UserControl
{
ProductProvider provider = new ProductProvider();
TBL_USER_PROFILEProvider uprovider = TBL_USER_PROFILEProvider();
DocumentProvider dprovider = new DocumentProvider();
int docType = 100;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string userName = SPContext.Current.Web.CurrentUser.Name;
TBL_USER_PROFILE p = uprovider.GetUser(userName);
if (p != null)
{
List<string> alist = uprovider.GetAccessByModuleName(p.UserProfileID, "Group 1");
if (alist.Count == 0)
Response.Redirect("/SitePages/AccessDeny.aspx");
}
}
}
}
Group1_UserControl.ascx: (with doctype hardcoded)
<a href="#" onclick="openDialog('/SitePages/FileDownload.aspx?DocType=100&ItemNo=<%#Eval("StoreItemNo")%>&CustomerID=<%#Eval("CustomerID")%>')">
You will have to use AJAX for that. Then you can pass values from backend to JavaScript.
Below is an example,
Client Side Script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/YourFunctionHere",
data: '{name: "' + DocType + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
The Web Method
[System.Web.Services.WebMethod]
public static string YourFunctionHere(string name)
{
return "return value here";
}
My function
<script type="text/javascript">
function methodtocall(id) {
// My code
}
</script>
My ashx page
public class sampleClass : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
// here i need to call that method
}
}
yes i referred net.But no solutions for that. mostly they give solution to call from method to ashx or call from ajax.
can anyone direct me with correct thing?
Refer like this,
ClientScript.RegisterStartupScript(this.GetType(), "methodtocall", script, true);
as per code,
public class sampleClass : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
var id = "someid"; //implement the id that you want to pass to the Javascript function
ClientScript.RegisterStartupScript(this.GetType(), "methodtocall", id, true);
}
}
Hope this helps..!
reference Link : Link
you can do like this
context.Response.Write("<script type='text/javascript'>function closeCurrentTab(){var conf=confirm('Are you sure, you want to close this tab?');if(conf==true){close();}}</script>");
context.Response.Write("<script type='text/javascript'>closeCurrentTab();</script>");
I have a submit button and below is the code in the onClick event :
protected void btnSubmit_Click(object sender, EventArgs e)
{
...
ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", "alert('Submitted')", true);
}
This code works.
But the problem is when user go to next page by this:
Response.Redirect("page2.aspx");
and when click backspace to get back to page1 and,
before the reload,
the following message box appears!!
this problem happened again when we refresh(F5) the page1 after submiting
how will I solve this?
I tried:
1. if(isPostback)// before the alert
2. string message = "Submitted";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
In such case, you can implement a special code block to detect browser refresh as
private bool refreshState;
private bool isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
refreshState = bool.Parse(AllStates[1].ToString());
if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}
protected override object SaveViewState()
{
Session["ISREFRESH"] = refreshState;
object[] AllStates = new object[3];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(refreshState);
return AllStates;
}
In the button submit you can do it as
protected void btn3_Click(object sender, EventArgs e)
{
if (isRefresh == false)
{
Insert Code here
}
}
Is possible receive the parameters that were sent from the
IFrame code behind (id and pTmp) the javascript popup then send them to the page parent
Code IFrame
protected void btnConfirm_Click(object sender, EventArgs e)
{
EDPBLL = new EDPLogic();
int id = EDPBLL.Add(Convert.ToInt32(Request.QueryString["EDP"]), Convert.ToInt32(Session["userId"]), DateTime.Now, Convert.ToInt32(ddlPrensa.SelectedValue));
string numeroEDP = EDPBLL.generarNumeroEDP(id);
EDPBLL.UpdateEdpCode(id, numeroEDP);
Session["pEDPId"] = id;
Session["numeroEDP"] = numeroEDP;
int pTmp = 4;
ScriptManager.RegisterStartupScript(Page, GetType(), "Popup", "<script>Popup('"+id+"','"+pTmp+"')</script>", false);
}
The script simulates a click event of parent window
Code JavaScript .aspx
<script type="text/javascript">
function Popup() {
$("#MainContent_btnPrueba", window.parent.document).trigger("click");
}
</script>
Use this
<script type="text/javascript">
function Popup(var1, var2) {
$("#MainContent_btnPrueba", window.parent.document).trigger("click");
}
</script>
I am trying to create a demo of Group Chat using reverse ajax in Spring. I am using Spring 3.2.0.RELEASE version.
I am using DeferredResult to perform reverse ajax in my controller. Following is the snippet of my Controller class.
#Autowired
private AsyncRepository asyncRepository;
Map<Integer, List<DeferredResult<String>>> watchers = new ConcurrentHashMap<Integer, List<DeferredResult<String>>>();
#RequestMapping(value="/asyncRequest/getMessages/{id}", method=RequestMethod.GET)
#ResponseBody
public DeferredResult<String> getMessages(final #PathVariable("id") Integer id){
final DeferredResult<String> deferredResult = new DeferredResult<String>(null, Collections.emptyList());
if(watchers.containsKey(id)) {
watchers.get(id).add(deferredResult);
} else {
watchers.put(id, new ArrayList<DeferredResult<String>>());
watchers.get(id).add(deferredResult);
}
deferredResult.onCompletion(new Runnable() {
#Override
public void run() {
watchers.get(id).remove(deferredResult);
}
});
return deferredResult;
}
#RequestMapping(value="/asyncRequest/setMessages/{id}/{message}", method=RequestMethod.GET)
#ResponseBody
public String setMessage(#PathVariable("id") Integer id, #PathVariable("message") String message) {
asyncRepository.setMessage(id, message);
return "";
}
#Scheduled(fixedRate=1000)
public void processQueues() {
for (Map.Entry<Integer, Queue<AsyncDataBean>> entry : asyncRepository.getAsyncBeans().entrySet()) {
while(entry != null && entry.getValue() != null && !entry.getValue().isEmpty()) {
AsyncDataBean asyncDataBean = entry.getValue().poll();
for (DeferredResult<String> deferredResult : watchers.get(asyncDataBean.getId())) {
deferredResult.setResult(asyncDataBean.getMessage());
}
}
}
}
And below is the Repository class which holds the Map of GroupID and its relevant messageQueue. And it also has the functions for getting and setting the messages for relevant group id.
#Repository
public class AsyncRepository {
private Map<Integer, Queue<AsyncDataBean>> asyncBeans = new ConcurrentHashMap<Integer, Queue<AsyncDataBean>>();
public String getMessages(Integer id) {
StringBuilder stringBuilder = new StringBuilder();
while (asyncBeans.get(id) != null && !asyncBeans.get(id).isEmpty()) {
stringBuilder.append(asyncBeans.get(id).poll().getMessage()).append("~");
}
return stringBuilder.toString();
}
public void setMessage(Integer id, String message) {
if(asyncBeans.containsKey(id)) {
asyncBeans.get(id).add(new AsyncDataBean(id, message));
} else {
Queue<AsyncDataBean> messageQueue = new ConcurrentLinkedQueue<AsyncDataBean>();
messageQueue.add(new AsyncDataBean(id, message));
asyncBeans.put(id, messageQueue);
}
}
public Map<Integer, Queue<AsyncDataBean>> getAsyncBeans() {
return asyncBeans;
}
public void setAsyncBeans(Map<Integer, Queue<AsyncDataBean>> asyncBeans) {
this.asyncBeans = asyncBeans;
}
}
And below is the data bean I am using to store each message with its group id.
public class AsyncDataBean {
private Integer id;
private String message;
public AsyncDataBean() {
}
public AsyncDataBean(int id, String message) {
this.setId(id);
this.setMessage(message);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And then comes the jsp page for group chat. which looks like below.
<script type="text/javascript">
var messagesWaiting = false;
function getMessages(){
if(!messagesWaiting){
$.ajax({ url: "${pageContext.servletContext.contextPath}/asyncRequest/getMessages/${id}",
dataType:"text",
success: function(data,textStatus,jqXHR) {
if(textStatus == 'success'){
messagesWaiting = false;
var arr = data.split("~");
for(var i=0; i<arr.length; i++)
{
try
{
if(arr[i] != '') {
$("#txtaMessages").val($("#txtaMessages").val() + "\n\n" + arr[i]);
document.getElementById("txtaMessages").scrollTop = document.getElementById("txtaMessages").scrollHeight;
}
}
catch(e){
alert(e.message);
}
}
}
},
complete: function(j) {
},
error: function(xhr) {
}
});
messagesWaiting = true;
}
}
setInterval(getMessages, 1000);
getMessages();
function sendMessage() {
var xmlhttp1 = new XMLHttpRequest();
xmlhttp1.open("GET", '${pageContext.servletContext.contextPath}/asyncRequest/setMessages/${id}/' + $("#txtMessage").val(), true);
xmlhttp1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp1.send();
$("#txtMessage").val("");
$("#txtMessage").focus();
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<table>
<tr>
<td>Messages :: </td>
<td>
<textarea cols="100" rows="10" id="txtaMessages"></textarea>
</td>
</tr>
<tr>
<td>Send Message :: </td>
<td><input type="text" id="txtMessage"/></td>
</tr>
<tr>
<td><input type="button" value="Send" onclick="sendMessage();"/></td>
</tr>
</table>
</body>
</html>
That is what I have coded till now to get this working. And everything is working finw in FF and Chrome. But in IE it is not working as expected. The request is never gets hold on the server and it always gets executed every second as configured in the javascript code. And it always returns the same result as previous. I have tried to use several other methods to send ajax request for IE but its not working. Can anyone get it working for me?
Since everything works fine in FF and Chrome, I suspect the problem is with javascript code to send the request to get messages.
Please help me.
Thanks in advance.
This is very very frustrating.
To get this thing work properly in IE I need to set cache:false attribute in the ajax request I am creating with jquery for getMessages. Otherwise IE will not hold the request in pending status and always returns back with the old response text.
Its a very big issue with IE. I hope no one face the problem again or finds this answer as early as possible.
:)