create a form in placeholder in C# - c#

StringBuilder str=new StringBuilder();
str.Append("<div style='font-style:oblique;font-size:24px;text-align:left;margin-bottom:25px;'>");
str.Append("Products");
str.Append("</div>");
str.Append("<div style='font-style:oblique;font-size:18px;text-align:right;margin-bottom:25px;'>");
str.Append("<asp:TextBox ID='txtSearch' runat='server'></asp:TextBox> <asp:Button ID='btbSearch' runat='server' Text='Search'/>");
str.Append("</div>");
str.Append("<table width='100%' border='1' cellpadding='0' cellspacing='0'>");
In the second <div>, I try to create a textbox and a button and add them in the placeholder. When I debug with browser console, I see them in html code but it cannot show in the browser, it just show the table on browser. Is there any example to work these cases?

<asp: tags are entirely server side tags. They will be translated by the ASP engine into plain HTML tags.
By writing those tags to the response directly you bypass the ASP engine's ability to refactor them into proper HTML. When the browser gets them it doesn't know how to render them, so it just ignores them.
You should be creating the controls as objects, rather than as strings, for example:
TextBox txtSearch = new TextBox();
txtSearch.ID= "txtSearch";
placeHolder1.Controls.Add(txtSearch);
Button btbSearch = new Button();
btbSearch.ID = "btbSearch";
btbSearch.Text = "Search";
placeHolder1.Controls.Add(btbSearch);
Or, better yet, you could place that text in a markup file rather than using the code behind.

Most likely you are not generating ASPX page to render on server, but rather sending output of your StringBuilder to the browser. Since asp:TextBox and similar ASP.Net elements can't be rendered by browser you see nothing in a view (also nodes are present as they don't make HTML completely invalid).
You want to generate <INPUT...> elements instead of asp:TextBox to see output in browser.
Note: there are likely better way to achieve your goal (i.e. client side templates, or regular rendering in the view), but you need to spell your actual problem first.

You can use code like this
var tableBody=""; // here you have to define the table body yourself
var form=
new {
method=#"get", // decide for your request method get/post
action=#"http://www.google.com" // the page processes the request
};
var html=#"
<div style='font-style: oblique; font-size: 24px; text-align: left; margin-bottom: 25px'>Products</div>
<div style='font-style: oblique; font-size: 18px; text-align: right; margin-bottom: 25px'>
<form method='"+form.method+#"' action='"+form.action+#"'>
<input id='txtSearch' name='txtSearch'>
<input type='button' id='btbSearch' text='Search' onclick='this.parentNode.submit();'>
</form>
</div>
<table width='100%' border='1' cellpadding='0' cellspacing='0'>"+tableBody+#"
</table>
";
The fixed part code of html is not necessarily consist with StringBuffer. If you want to generate the html dynamically, consider to use LINQ.
What should be done yourself are in the comments of the code. Notice that the txtSearch is not only given an id, but also name.

Related

onserverclick not firing for input of type date

I am building a web application in ASP.NET using webforms.
I have an input html element which I have set to run at server and I want to fire an event whenever the date is changed.
<input id="datePicker" class="form-control" style="display: inline; margin-left: 5px; width: 15%; text-align: center;" type="date" runat="server" onserverclick="Date_Changed"/>
I have the event in my codebehind:
protected void Date_Changed(object sender, EventArgs e) {}
However, the event is never fired.
Don't believe that server side click events can be wired up to a input that way (using the onserverclick).
I would consider dropping in a HTML button, say like this:
<button id="datePicker"
class="form-control"
style="display: inline; margin-left: 5px; width: 15%; text-align: center;"
type="date"
runat="server" onserverclick="Date_Changed" />
And even better yet, drop in a asp.net button.
If you drop in a input tag, then I don't think you can get the asp.net system to wire this up for you. You could I suppose write this:
(this is what a plane jane above button becomes:
<input onclick="__doPostBack('Button11','')"
name="Button11" type="button" id="Button11" value="button">
So you could try above - but using a "input" tag I don't believe will work, but try a HTML button as per above - that does allow "on server click".
Do keep in mind that if you drop in a asp.net text box, and set textmode = "date"?
Say like this:
<asp:TextBox ID="MyDateTest" runat="server" TextMode="date">
</asp:TextBox>
Then you see this:
So, above is a built in feature - you don't need any js, bootstrap, or anything at all.
but, you could add a "client" side click to your markup, as I posted a above the do post-back would (should) run your click event. However, it probably a whole lot better to not fight asp.net, since then you quite much hand coding a lot of HTML, and doing that means you quite much toss out most of the features of why you would use asp.net in the the first place (that means to take advantage of all the built in controls, and the pre-processing of those controls for you).

How to get ValidationMessage in MVC View without HTML helper adding its own span?

First off , I am new to MVC. I have a view which has the following line of code:
<span id="loginerror" style="border-color:red;"> #Html.ValidationMessage("UserName") </span>
This works fine except that it adds a span within my loginerror instead of just displaying the error within loginerror . I am aware that I can also add css through html helper but I would like to do it in this way if possible. I just want to get the value of ValidationMessage without having to change a lot of code.
The #Html.ValidationMessage() helper outputs a <span> element, which assuming the property is valid is
<span class="field-validation-valid" data-valmsg-for="xxx" data-valmsg-replace="true"></span>
and if the property is invalid
<span class="field-validation-error" data-valmsg-for="xxx" data-valmsg-replace="true">Error message</span>
For client side validation, the jquery.validate.js and jquery.validate.unobtrusive.js files add an inner span for the error message which is
<span class="field-validation-error" data-valmsg-for="xxx" data-valmsg-replace="true">
<span for="xxx" generated="true" class="">Error message</span>
</span>
In order to change this behavior, you would need to create your own HtmlHelper extension method for the outer <span> element or use MVC-5 which has overloads that allow you to add a parameter specifying the tag.
However, for the inner span element generated by client side validation, you would need to modify the jquery.validate.unobtrusive.js file and it should be obvious that this is not something you would want to do.
Instead you can just create your own css file to style the default span elements, for example
field-validation-error {
display: inline-block;
border: solid 1px red;
color: green;
margin: 10px;
}

asp:Literal strips out title attribute value

I am working on a asp.net website (web forms and mvc) where asp:Literal is used in a few pages.
I needed to change the content of one page to add a simple title attribute to the existing tag.
So i need the rendered result to be:
<a href="test.jpg"
title="title here"
id="testimage"
rel="hint-text: CLICK TO ZOOM"
style="position: relative; display: inline-block">image goes here</a>
But after rendering, it looks like that:
<a href="test.jpg"
title id="testimage"
rel="hint-text: CLICK TO ZOOM"
style="position: relative; display: inline-block">image goes here</a>
At first i thought it could be something to do with the controls Mode property, but even if i change the Mode to PassThrough it still does not render the value of the tittle attribute.
EDIT: The code for the literal is as folows:
LiteralControl.Text = "<a href='test.jpg' title='title here' id='testimage' rel='hint-text: CLICK TO ZOOM' style='position: relative; display: inline-block'>image goes here</a>"
Does any of you guys have this problem and happens to know the solution?

How to modify the HTML in Javascript and then read the changes in ASP.NET on the postback?

This is a two-fer, and I've looked in a lot of places and could not put together a solution for this particular scenario.
I will have the user enter multiple values using a single text field, such as:
<div style="margin-left: 5px; display: block;">
<div id="divTemplateLine" style="display: none;">
x
</div>
</div>
Using Javascript, the Add button will keep cloning divTemplateLine and include the text within the parent node.
I got all that working fine.
Now, I'd like to read all these lines (salmon, soup, miso, japanese) on the postback.
I'm assuming at this point I'm in the realm of parsing HTML, since these div's I added are not "runat" server.
One answer could be using a server-run hidden value, where the Javascript will keep appending to it.. yes that's a good solution, but I'd like to see how I can parse out the HTML elements and nodes just as I did in Javascript, because my real scenario is more complicated than a single value, so a hidden value will not quite do.
Any input and/or judgment is welcome.
The solution is to keep two versions of your data, one that you show on the user, and one on a hidden input that you post back and get the data that user select and keep.
For example, when your user enter the 'salmon', you place it both on html render, and on an input hidden control with your way of serialize. When your user remove it, you remove it from your hidden control also.
At the end you going to have something like that, and you post it back and analyse it and save it on your database.
<input name="final_select" type="hidden" value="salmon;soup;miso;japanese" />
#BeemerGuy: take one text box and auto complete extender as follows:
<asp:TextBox ID="txtCustName" AutoPostBack="true" AutoComplete="off" runat="server"
OnTextChanged="txtCustName_TextChanged" />
<cc1:AutoCompleteExtender ID="ace1" TargetControlID="txtCustName" ServiceMethod="GetCustomers"
MinimumPrefixLength="1" OnClientItemSelected="ace1_itemSelected" FirstRowSelected="true"
runat="server" />
Auto Complete Extender has service method property which will be called when you enter text on text box and will add text box value in list view
<<****** Webmethod code is here ******>>
ListBox list = new ListBox();
[WebMethod]
public static DataSet GetCustomers(string prefixText)
{
list .Items.Add(New ListItem(prefixText, 0));
}

Pass values to javascript in ASP.NET

I have an ASP textbox control where I need to execute some javascript function when the OnClick event occurs. I need to pass to that javascript function two IDs of other controls on that page. My textbox markup is as follows:
<asp:TextBox ID="txtMonthDisplay" runat="server" Style="border-top: none; border-left: none;
border-right: none; border-bottom: solid 1px blue; cursor: pointer; color: Blue;
width: 35px;" EnableViewState="True" MaxLength="3" onClick="javascript: ShowBox('<%= divYear.ClientID%>', '<%= txtYearDisplay.ClientID %>');"></asp:TextBox>
But whenever it calls the javascript function I have setup an alert to check the incoming values, and they are simply <%= txtYearDisplay.ClientID %> and <%= divYear.ClientID%>. Not the actual IDs of those controls.
What am I missing here, or doing incorrectly? I'm not well versed with asp.net so server vs. client side is a bit fuzzy for me.
Thanks
You can't Response.Write (<%= %> is shorthand for Response.Write) into a server tag (usually).
Instead, you can write your onclick handler in the codebehind:
txtMonthDisplay.Attributes["onclick"] = string.Format(
"ShowBox('{0}', '{1}');",
divYear.ClientID,
txtYearDisplay.ClientID);
By the way, you don't need the javascript: prefix. That is only necessary when setting the href of a link to execute script. It is not needed for event handlers such as onclick.
Then pass the variables from codebehind:
protected void Page_Load(object sender, EventArgs e){
txtMonthDisplay.Attributes.Add("onClick",
String.Format("ShowBox('{0}','{1}')",
divYear.ClientID,
txtYearDisplay.ClientID));
}
The <%= ... %> displaying expression is an equivalent of the embedded code block that contains only the Response.Write(…) statement. This is the simplest way to display information such as a single string, an int variable, or a constant.
Remember that the displaying expression cannot be used in the attributes of server controls. This is because the .NET Framework directly compiles the whole expression instead of the displaying content as the value to the attribute.
http://support.microsoft.com/kb/976112/en-us
Hmm, your markup looks correct, I would try a couple of things, first try adding the onclick event through code and see if the IDs get added. That way you will know if your textbox generation works correctly.
You could also work around by doing click binding after the document.ready using JQuery and having the values as hidden values on the form.

Categories