Send button from c# to client side - c#

I have a helper created as follows:-
public static MvcHtmlString FileDomElement(this HtmlHelper helper, FileUpload fileUpload)
{
string strOutput = string.Empty;
if (fileUpload.MultipleFile)
{
if (string.IsNullOrEmpty(fileUpload.MimeType))
{
strOutput = "<input type=\"file\" multiple=\"multiple\" id=\"chooseFiles\" value=\"Choose File(s)\" onchange=\"ehDisplayFileNames();\" style=\"opacity: 0\" >";
}
else
{
strOutput = "<input type=\"file\" multiple=\"multiple\" id=\"chooseFiles\" value=\"Choose File(s)\" accept=\"" + fileUpload.MimeType + "\" onchange=\"ehDisplayFileNames();\" style=\"opacity: 0;\">";
}
}
else
{
if (string.IsNullOrEmpty(fileUpload.MimeType))
{
strOutput = "<input type=\"file\" id=\"chooseFiles\" value=\"Choose File(s)\" onchange=\"ehDisplayFileNames();\" style=\"opacity: 0;\">";
}
else
{
strOutput = "<input type=\"file\" id=\"chooseFiles\" value=\"Choose File(s)\" accept=\"" + fileUpload.MimeType + "\" onchange=\"ehDisplayFileNames();\" style=\"opacity: 0;\">";
}
}
return MvcHtmlString.Create(strOutput);
}
Now in the onchange event of the file I want to send the button to the backend. Because I have multiple file input elements on a single page. So I want to detect which one was clicked.
Please help me with this.
Thanks
Abhishek

You could try catching the event info and using that to get a reference to the sender:
function ehDisplayFileNames(event) {
console.log(event.target.id + ' has fired the event!');
}
Your markup would need to send the event:
onchange="ehDisplayFileNames(event);"
Mark's comment above is very true, once you have a client side id you will still need some type of Ajax call to get this info back to the server.

Related

Adding Newline in string for HTML email body

I'm trying to generate an email with some basic formatting based on labels in a FormView. I'm going the route of Process.Start("mailto:... instead of System.Net.Mail so the email opens up in the default email client to give the user a chance to edit To: CC: etc without making a new form just to handle that. I've got the following code-behind to handle an "Email Form" button for emailing the URL of the webform.
protected void fvBF_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Email")
{
Label lblBFID = (Label)fvBookingForm.FindControl("lblBFID");
Label lblProjectID = (Label)fvBookingForm.FindControl("lblProjectNum");
Label lblProjectName = (Label)fvBookingForm.FindControl("lblProjectName");
Label lblReleaseName = (Label)fvBookingForm.FindControl("lblReleaseName");
Label lblPMName = (Label)fvBookingForm.FindControl("lblPM");
String strReleaseName = String.IsNullOrEmpty(lblReleaseName.Text) ? "[Description]" : lblReleaseName.Text;
String pmFirst = lblPMName.Text.ToString().Split()[0];
String pmLast = lblPMName.Text.ToString().Split()[1];
String strSubject = "BF " + lblBFID.Text + " - " + lblProjectName.Text + " - Release " + strReleaseName;
String strBody = "A Booking Form for Project #"+ lblProjectID.Text + " - " + lblProjectName.Text +
" - Release " + strReleaseName + " has been created or modified. \n\n" + Request.Url.ToString();
Process.Start("mailto:" + pmFirst + "." + pmLast + "#company.com?subject=" +
HttpUtility.HtmlAttributeEncode(strSubject) + "&body=" +
HttpUtility.HtmlAttributeEncode(strBody).Replace("\n", Environment.NewLine));
}
}
However, when the email is generated, there are no line breaks in the body between the "A Booking Form...." sentence and the URL. I've tried putting Environment.NewLine directly in the string.
...created or modified. " + Environment.Newline + Environment.NewLine + Request.Url.ToString();
Which basically gives me the same results. I've tried replacing the \n with <br /> which doesn't add the line break and for some reason, doesn't display the URL either. I can only guess that the problem has to do with the HtmlAttributeEncode() and getting it to parse the NewLine properly. Is there something I'm missing here?
You might want to try .Replace("\r\n", "<br />") on the body after you have done your encoding of the body.
You should probably use StringBuilder here instead of String.
You can then do the following:
StringBuilder builder = new StringBuilder();
builder.AppendLine(string.Format("A Booking Form for Project #{0} - {1}",lblProjectID.Text, lblProjectName.Text));
builder.AppendLine(string.Format(" - Release {0} has been created or modified.", strReleaseName));
builder.AppendLine();
builder.AppendLine(Request.Url.ToString());
String strBody = builder.ToString();
You can also include (char)10 and (char)13 in your string creation. e.g.:
string.Format("First Line{0}{1}Second Line", (char)10, (char)13);
Model.Message = "my message \n second message";
then add this style to string tag style="white-space: pre-line;"
example <h3 style="white-space: pre-line;">#Model.Message</h3>

how to place text inside quotes

I'm trying to add your computer name to the name of the plugin text. Here is a example:
I have a path which detects file which is here:
string pypath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
+ "\\elfen_encore\\extra_maya\\mayaplugins\\CoDMayaTools.py";
From there I use this code to access a string in there
public void changepy()
{
if (File.Exists(pypath))
{
{
string quotes = "\"\"";
string name = System.Environment.MachineName;
string text = File.ReadAllText(pypath);
text = text.Replace("\"Call of Duty Tools\"", quotes + name);
File.WriteAllText(pypath, text + name);
}
MessageBox.Show("Changed ");
}
else
{
}
Then this is the file it should change to computer name :
OBJECT_NAMES = {'menu' : ["CoDMayaToolsMenu",
"Call of Duty Tools", None, None, None],
"CoDMayaToolsMenu" is the issue; I want to replace that with the users computer name but as you can see its in quotes and I am having huge issues on trying to get the text in the quotes. How can I solve it?
Is this what you are trying to do?
text = text.Replace("\"Call of Duty Tools\"", "\"" + name + "\"");
If not, please specify a little bit more your question or your desired output.
If you're leaving the quotes anyway, why not this approach? ... It's a bit unclear if this is what you're trying to accomplish?
public void changepy()
{
if (File.Exists(pypath))
{
string machineName = System.Environment.MachineName;
string content = File.ReadAllText(pypath);
content = content.Replace("Call of Duty Tools", machineName);
File.WriteAllText(pypath, content);
MessageBox.Show("Changed");
}
else
{
}
}

Confused on some webBrowser functions

public void PortalLogin()
{
string portalUrl = "URL";
string portalEmail = "email";
string portalPassword = "password";
// Run when page finishes navigating
webBrowser2.DocumentCompleted += (s, e) =>
{
HtmlElement head = webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript = webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)testScript.DomElement;
element.text = "function PortalLogin() { document.getElementById('username').value = '" + portalEmail + "'; document.getElementById('password').value = '" + portalPassword + "'; document.getElementById('credentials').submit(); }";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("PortalLogin");
};
// Navigate to the portal
webBrowser2.Navigate(portalUrl);
while (this.webBrowser2.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
}
I have the code segment above that is supposed to Navigate to a specific URL and then upon Navigate's completion, execute invoke a script to login to the webpage there. Now, because the entire PortalLogin() function is inside of a while loop, I have to include the:
while (this.webBrowser2.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
segment so that the while loop doesn't just interrupt the Navigate function a ton. However, the code isn't quite working, the flow seems to be off when I step through it with breakpoints. I think part of the problem is I don't quite understand how the while loop testing ReadState != Complete works. Could someone enlighten me?
Better use WebClient with cookies or HttpWebRequest and HttpWebResponse.

asp.net Button type link should open on new window

using c# .net4.0
I am aware the asp.net button with in the gridview of type link does a post to the same page when clicked, i need make several manipualtion on server side before actually redirecting user to an external site hence i can't use Hyperlinkfield. What i need now is the external site htm page should open up in sperate window. I tried the following which works but source site's fonts get bigger???
heres what i tried
Response.Write("<script>");
Response.Write("window.open('http://www.google.co.uk','_blank')");
Response.Write("</script>");
Response.End();
may be i need a refresh source site??
Thanks
# Curt Here is the code for Hyperlink i tired
on page load added new button on gridview
HyperLinkField LinksBoundField = new HyperLinkField();
string[] dataNavigateUrlFields = {"link"};
LinksBoundField.DataTextField = "link";
LinksBoundField.DataNavigateUrlFields = dataNavigateUrlFields;
LinksBoundField.DataNavigateUrlFormatString = "http://" + Helper.IP + "/" + Helper.SiteName + "/" + Helper.ThirdPartyAccess + "?dispage={0}&token=" + Session["Token"];
LinksBoundField.HeaderText = "Link";
LinksBoundField.Target = "_blank";
GridViewLinkedService.Columns.Add(LinksBoundField);
GridViewLinkedService.RowDataBound += new GridViewRowEventHandler(grdView_RowDataBound);
to append external values (refe and appid) to navigate url
protected void grdView_RowDataBound(object sender, GridViewRowEventArgs e)
{
string strvalue = "";
string strvalue1 = "";
string strRef = "";
string strAppId = "";
foreach (GridViewRow row in GridViewLinkedService.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
//reference and appid
strAppId = row.Cells[0].Text;
strRef = row.Cells[1].Text;
HyperLink grdviewLink = (HyperLink)row.Cells[5].Controls[0];
strvalue = grdviewLink.NavigateUrl;
strvalue1 = Regex.Replace(strvalue, "(.*dispage\\=).*/(services.*)", "$1$2");
grdviewLink.NavigateUrl = "~/My Service/FillerPage.aspx?nurl=" + strvalue1 + "&AppID=" + strAppId.ToString() + "&Ref=" + strRef.ToString();
}
}
}
public partial class FillerPage : System.Web.UI.Page
{
private string refno = null;
private string appid = null;
private string nurl = null;
private string strvalue1 = "";
private string newtoken = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString.GetValues("AppID") != null)
{
appid = Request.QueryString.GetValues("AppID")[0].ToString();
}
if (Request.QueryString.GetValues("Ref") != null)
{
refno = Request.QueryString.GetValues("Ref")[0].ToString();
}
if (Request.QueryString.GetValues("nurl") != null)
{
nurl = Request.QueryString.GetValues("nurl")[0].ToString();
}
while receiving the long url it gets messed up(same query multiple times and all jumbled up)?????
is there a better way to pass parameters ???
you need to register script not response.write
so the code for you is :
ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script language=JavaScript>window.open('http://www.google.co.uk','_blank')</script>");
Read more : ClientScriptManager.RegisterStartupScript.
In a situation where I need to run server side code, before then opening a new page, I sometimes create a Generic Handler File and link to this with a HyperLink, passing variables as Query Strings. Therefore something like:
/MyGenericFile.ashx?id=123
In this file, I would have some scripting that needs to be carried out, followed by a Response.Redirect().
As long as the HyperLink is set to target="_blank", the user won't even know they've been to a generic file, which is then redirected. It will appear as they've opened a new link.
Therefore the process would be:
User clicks link to .ashx file
Link opens in new window
Necessary scripting is ran
Response.Redirect() is ran
User is taken to web page (www.google.com in your example)
I believe this same process is used by advert management systems to help track clicks.
You can register a script to run on page load with ClientScriptManager.RegisterStartupScript.

Sending querystring variable to new popup window

My JavaScript code is this:
var newwindow;
function poptastic(url) {
newwindow = window.open(url, 'name', 'height=400,width=200');
if (window.focus) { newwindow.focus() }
}
And my C# code:
foreach (GridViewRow row in GvComments.Rows)
{
Button btnReplay = (Button)row.FindControl("btnReplay");
string url = "javascript:poptastic('Configuration.aspx?id=" + e.CommandArgument + "')";
btnReplay.Attributes.Add("onclick", url);
}
I think the C# code has problem, because when I use this JavaScript code in a tag it works, but in attribute.add not working.
Try using OnClientClick for this instead:
btnReplay.OnClientClick = String.Format("poptastic(\"Configuration.aspx?id={0}\");return false;", e.CommandArgument);
EDIT
Here's a JavaScript function you can use to open popup windows:
openChildWindowWithDimensions = function(url, width, height, showMenu, canResize, showScrollbars) {
var childWindow = window.open(url, "", "\"width=" + width + ",height=" + height + ",menubar=" + (showMenu ? "1" : "0") + ",scrollbars=" + (showScrollbars ? "1" : "0") + ",resizable=" + (canResize ? "1" : "0") + "\"");
if (childWindow){
childWindow.resizeTo(width, height);
childWindow.focus();
}
}
This problem would be very easy to answer, if you can provide the HTML generated. To find HTML generated go the browser window where you are seeing the rendered page and do a View Source. See How do I check my site's source code
With the code you have provided all the suggestions I can make are already made by #James Johnson
Please see a minor correction to James code
btnReplay.OnClientClick = String.Format("poptastic('Configuration.aspx?id={0}');return false;", e.CommandArgument);
Note: I have changed \" to '

Categories

Resources