initialize html controls in asp.net - asp.net

If I have an html input "<input id="score1" type="text" value=""/>" and want to initialize it on the c# page load, but I don't want to use asp controls.How do I do it?
Thanks

You can use server-side plain HTML controls, by just using runat="server".
For instance:
<input type="text" runat="server" id="myTextBox" />
// ...and then in the code-behind...
myTextBox.Value = "harbl";

<input id="score1" type="text" runat="server" value=""/>
Then in your page's load event:
score1.Value = "some value";

You could set a property on the page codebehind, the access the property on the page
public class MyPage
{
public string InputDefaultContent { get; set; }
private void Page_Load(object s, EventArgs e)
{
InputDefaultContent = "Blah";
}
}
then on the page
<input type="text" value="<%= InputDefaultContent %>" />

<input type='text' value='default value' />

Related

Razor Pages action from input button

I'm trying to understand how Razor pages work, as well as .Net Core, by creating a small web application and I'm stuck on how to handle the button action within a form. I'm used to the MVC type of process (from when I first tried web apps 5 years ago) where the button would have a onClick action that could be accessed from the code behind but it seems like that's not the same with a Razor page (unless I'm just not seeing it). I have a basic form like this
<form method="post">
<fieldset>
<input type="text" value="" placeholder="user name"/>
<input type="password" value="" placeholder="password"/>
<input type="button" value="Submit" id="submitButton"/>
</fieldset>
So what I'm trying to achieve is when the button is pressed an action in the .cs file is called that will perform a couple different operations (like calling an API, getting a result and then depending on result route to a different page) but even if I add an "onClick" to the button I can't figure out how to hook it up to the code behind. I've seen various answers, most using models and a database but since that's not the same as what I'm doing those examples haven't helped.
I will try to make a simple example for you. Create a razor page and use the name "Test". The Test.cshtml file should have the following contents:
#page
#model WebApplication1.Pages.TestModel
<form method="post">
<fieldset>
<input asp-for="username" placeholder="user name" />
<span asp-validation-for="username" class="text-danger"></span>
<br />
<input asp-for="password" type="password" placeholder="password" />
<span asp-validation-for="password" class="text-danger"></span>
<br />
<input type="submit" value="Submit" id="submitButton" />
</fieldset>
</form>
The Test.cshtml.cs should have the following contents
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace WebApplication1.Pages
{
public class TestModel : PageModel
{
[BindProperty]
public string username { get; set; }
[BindProperty]
public string password { get; set; }
public void OnGet()
{
// you can initialize the values. for example I set the username
username = "test";
}
public IActionResult OnPost()
{
// do something with username and password
if (string.IsNullOrEmpty(password))
{
ModelState.AddModelError("password", "Password is a required field.");
return Page();
}
// or you can redirect to another page
return RedirectToPage("./Index");
}
}
}
Tell me if you need extra explanation for this example. I hope it helps.

form POST in ASP.NET page

I am trying to implement a paypal payment in my .aspx page. I have the following html in my page:
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="hosted_button_id" value="19218">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="business" value="<%= ConfigurationManager.AppSettings("BusinessEmail").ToString%>">
<input type="hidden" name="item_name" value="<%= "CityBits Gold " & listplans.SelectedItem.ToString & " listing plan for " & trim(txttitle.text)%>">
<input type="hidden" name="item_number" value="<%= HiddenFieldid.Value%>">
<input type="hidden" name="amount" value="<%= listplans.SelectedValue%>">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="return" value="<%= ConfigurationManager.AppSettings("ReturnUrl").ToString & "?requestID=" & HiddenFieldid.Value%>">
<input type="hidden" name="cancel_return" value="<%= ConfigurationManager.AppSettings("CancelUrl").ToString%>">
<input type="hidden" name="no_shipping" value="1">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
In my aspx page, when i click the paypal button, it just refresh the page. When I put the exact same code (with actual values of course) in a plain html file and click the button, it redirect me to paypal as desired. I have tried using actual values for inputs just like in the html page, but it still does not work.
if it matters, I have update panels in my page, but this form is not inside them.
Anyone knows what I am doing wrong? It might be something stupid, but this is giving me headaches for 2 days now!
The problem here is the way ASP.NET pages work. ASP.NET always assumes only one large form on the page, and begins to perform various tricks when you introduce a second one.
However what you can use in your case is a Button control and its PostBackUrl property. It will handle your inner form correctly, gathering all parameters and performing a post:
<form target="paypal">
...
<asp:ImageButton runat="server" ID="PayPalSubmit"
PostBackUrl="https://www.paypal.com/cgi-bin/webscr"
ImageUrl="https://www.sandbox.paypal.com/en_US/i/btn/btn_cart_LG.gif" />
</form>
This is a well-known issue with ASP.NET forms when trying to post data to PayPal. Here's a really cool solution that I use all the time for E-Commerce Web Forms applications:
http://jerschneid.blogspot.com/2007/03/hide-form-tag-but-leave-content.html
And here are two personal blog posts expanding on Jeremy Schneider's idea of using a custom version of HtmlForm:
http://codersbarn.com/post/2008/03/08/Solution-to-ASPNET-Form-PayPal-Problem.aspx
http://codersbarn.com/post/2008/03/27/Integrate-PayPal-Checkout-Button-with-ASPNET-20.aspx
Stay away from using double form tags, JavaScript and other hacks.
using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
/// <summary>
/// This is a special form that can _not_ render the actual form tag, but always render the contents
/// </summary>
public class GhostForm : System.Web.UI.HtmlControls.HtmlForm
{
protected bool _render;
public bool RenderFormTag
{
get { return _render; }
set { _render = value; }
}
public GhostForm()
{
//By default, show the form tag
_render = true;
}
protected override void RenderBeginTag(HtmlTextWriter writer)
{
//Only render the tag when _render is set to true
if (_render)
base.RenderBeginTag(writer);
}
protected override void RenderEndTag(HtmlTextWriter writer)
{
//Only render the tag when _render is set to true
if (_render)
base.RenderEndTag(writer);
}
}

Declaring asp.net control inside HTML markup

Is it possible to write something like this?
<input class="form-control" id="name" name="name"
placeholder='<asp:Label runat="server" ID="lblFormName"></asp:Label>' type="text" required autofocus />
Solution 1: let ASP.Net render extra attributes
You can use the native TextBox control :
<asp:TextBox runat="server"
ID="name"
required="required"
autofocus="autofocus"
CssClass="form-control"
placeholder="myplaceholder" />
Extra attributes (ones that are not properties of the TextBox class), will be rendered as is:
Html result:
<input name="ctl00$MainContent$name"
type="text"
id="MainContent_name"
class="form-control"
required="required"
autofocus="autofocus"
placeholder="myplaceholder" />
If the generated id must be explicit, you can add CliendIDMode="Static":
<asp:TextBox runat="server"
ID="name"
required="required"
autofocus="autofocus"
CssClass="form-control"
placeholder="myplaceholder"
ClientIDMode="Static" />
Result:
<input name="ctl00$MainContent$name"
type="text"
id="name"
class="form-control"
required="required"
autofocus="autofocus"
placeholder="myplaceholder" />
Solution 2: write your own control
An even better approach is to extend the textbox class:
using System.Web.UI.WebControls;
namespace WebApplication1.Controls
{
public class TextBoxEx : TextBox
{
protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
if (AutoFocus) writer.AddAttribute("autofocus", "autofocus");
if (Required) writer.AddAttribute("required", "required");
if (!string.IsNullOrEmpty(PlaceHolder)) writer.AddAttribute("placeholder", PlaceHolder);
base.AddAttributesToRender(writer);
}
public string PlaceHolder
{
get {
var obj = ViewState["PlaceHolder"];
return obj != null ? (string)obj : default(string);
}
set { ViewState["PlaceHolder"] = value; }
}
public bool AutoFocus
{
get {
var obj = ViewState["AutoFocus"];
return obj != null ? (bool)obj : default(bool);
}
set { ViewState["AutoFocus"] = value; }
}
public bool Required
{
get {
var obj = ViewState["Required"];
return obj != null ? (bool)obj : default(bool);
}
set { ViewState["Required"] = value; }
}
}
}
Then you can register and use the control:
<%# Register Assembly="WebApplication1" TagPrefix="local" Namespace="WebApplication1.Controls" %>
....
<local:TextBoxEx runat="server" required="true" autofocus="true" PlaceHolder="my placeholder" />
You want to assign some value to one of HTML element's properties?
<asp:HiddenField runat="server" ID="lblFormName" />
<input class="form-control" id="name" name="name" placeholder='<%# lblFormName.Value %>' ...
Then you pass lblFormName.Value from CodeBehind.
You cannot declare a single ASP.NET control in a pure HTML page. It must be a ASP.NET page (aspx) which is processed by the server.

Submit form (without runat=server) from aspx page

as we all know there is only one form possible on aspx page. How can I add html form to aspx page from code begind and submit data of this created form?
Here is form example:
<form name="payment" method="post" action="https://sci.interkassa.com/" accept-charset="UTF-8">
<input type="hidden" name="ik_co_id" value="51237daa8f2a2d8413000000" />
<input type="hidden" name="ik_pm_no" value="ID_4233" />
<input type="hidden" name="ik_am" value="1.44" />
<input type="hidden" name="ik_desc" value="Payment Description" />
<input type="submit" value="Pay">
</form>
I have and idea to build string using ClientScriptManager first and than attach this form to div using jQuery. Something like that. Is there some bettre ideas?
I'm going to use something like that, but I don't like this solution:
Dim sname As [String] = "Interkassa"
Dim stype As Type = Me.[GetType]()
Dim cs As ClientScriptManager = Page.ClientScript
If Not cs.IsStartupScriptRegistered(stype, sname) Then
Dim sb As New StringBuilder()
sb.Append("<script type=text/javascript>")
sb.Append("$(document).ready(function () { var s = ""<form name='payment' method='post' action='https://sci.interkassa.com/' accept-charset='UTF-8'><input type='submit' value='Оплата через Интеркассу'></form>"";")
sb.Append("html = $.parseHTML(s);$('#interkassa').append(html);});")
sb.Append("</script>")
cs.RegisterStartupScript(stype, sname, sb.ToString())
End If
You don't need to add the HTML using code behind. That's a bad practice because it provides poor separation between logic and markup. Instead, create a button on your page where it fires a server side event, then have your server side event handle the logic.
<asp:Panel runat="server" ID="MyPaymentPanel">
<asp:Button runat="server" ID="SubmitPaymentBtn" Text="Pay" OnClick="SubmitPaymentBtn_Click" />
</asp:Panel>
Then in your code behind...
protected void SubmitPaymentBtn_Click(object sender, EventArgs e)
{
//Retrieve values for ik_co_id, ik_pm_no etc from your database
//post the form if sending to a site you don't control, or update your database if you control sci.interkassa.com
}
Try like this
<button id="ClearButton" class="Button2" onclick="javascript:temp();return false;">CLEAR</button>
<script type=text/javascript>
Function temp
{
// your code
}
</script>

Password-Box not showing any content

I have a small websolution that needs the user to input a password. I have two input boxes
<input type="password" runat="server" id="m_txtPassword1"/>
If I set some chars to the Value-property of the control like this:
m_txtPassword1.Value="someChars";
The password box is rendered empty. No bullets are shown. If I look into the rendered html-source, also no value-tag has been rendered. If I change the type to
<input type="text" runat="server" id="m_txtPassword1"/>
the chars are shown. Is this by design? How can I disable this feature?
Please note, I don't want to put a real password into the value-property, I only want to show the user that there is already a password set, and this is IMO done best with some 8 bullets in the input-control. But for this, I need the possibility to set the value-property of the control.
Update
For all, having the same problem: I have tried to declare <asp:textbox id="m_txtPassword1" runat="server" TextMode="Password" /> with the same result. Also m_txtPassword1.Attributes["value"]="someChars" has not helped.
It seems that this is realy not possible.
As a workaround, I declared the password-boxes as plain html without the runat="server" and have set the value-property in markup (via two properties from the code-behind). Not nice but I really want to show the user that he has already entered a password.
Another workaround would be to set the value through javascript on load.
This is by default. You cannot set a password.
I make this works,
<html>
<head>
<script type="text/javascript">
function alertValue()
{
alert(document.getElementById("password1").value);
}
function setpassword()
{
password1.value="someChars";
}
</script>
</head>
<body>
<form>
<input type="password" id="password1" value="" />
<input type="button" id="button1" onclick="alertValue()" value="Show default value" />
<input type="button" id="button2" onclick="setpassword()" value="Set value" />
</form>
</body>
</html>
Try this:
http://jsbin.com/ocexo5
It is by design, for security reasons - so that the password is not in the
HTML in plain text.
Now, you could write out javascript to set the value property of the textbox
on the client, of course this would still mean that you have the password in
plain text in the HTML.
Here is example of the page:
Markup:
<script type="text/javascript">
function setPwd()
{
var Pwd = "<%=Pwd %>";
var txtText = document.getElementById("MainContent_txtText");
txtText.value = Pwd;
}
</script>
<input type="password" id="txtText" runat="server"/>
And code-behind:
public partial class _Default : System.Web.UI.Page
{
public string Pwd;
protected void Page_Load(object sender, EventArgs e)
{
Pwd = "password";
ClientScript.RegisterStartupScript( this.GetType(),"somescript","setPwd();",true);
}
}
Textbox11.Attributes.Add("Value",whatever_your_password_is)

Resources