I am getting the System.String[] Error when trying to post data from a form below is my sample code.
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox id="AccidentDetailsDate" runat="server" />
<br /><br />
<asp:Button ID="Button1" Text="Submit" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
var AccidentDate = Request.Form.GetValues("AccidentDetailsDate");
Response.Write(AccidentDate);
}
}
If anyone could help me over this hurdle it would be much appreciated, I have spent the last 3 hour trying to resolve it!
In the page_load event try the following:
var AccidentDate = this.AccidentDetailsDate.Text;
Response.Write(AccidentDate);
Since AccidentDetailsDate is a text box you can access it in the code behind using the above syntax.
That's right, because you are getting array back, of all form elements named "AccidentDetailsDate".
Sounds like you want a single value:
var AccidentDate = Request.Form["AccidentDetailsDate"];
Response.Write(AccidentDate);
You are getting the error because of line:
Response.Write(AccidentDate);
Since your AccidentDate is a string[], where as Response.Write expects a single string value.
The problem is because of the earlier line, you are using Request.Form.GetValues, which would return an array of string, You don't have to use Request.Form, since your TextBox is already marked as runat="server", you can simply do:
var AccidentDate = AccidentDetailsDate.Text;
So your code should be:
public void Page_Load(object sender, EventArgs e)
{
var AccidentDate = AccidentDetailsDate.Text;
Response.Write(AccidentDate);
}
From the name of the control it appears that you are trying to get DateTime from user, you should parse it to DateTime in .Net framework or use a DateTimePicker
Try adding ToString() like this.
var AccidentDate = Request.Form.GetValues("AccidentDetailsDate").ToString();
Response.Write(AccidentDate);
Related
I have an ASP.net WebForm. The markup is like:
<div>
<input type="text" id="input" runat="server" value=" " />
<asp:Button Text="send" OnClick="btnsend_Click" ID="btnsend" runat="server" />
</div>
This HTML is generated at runtime . The events are defined in the code behind file.
I need to add these controls at runtime. I tried to use the Literal-Control but the controls are working just like HTML Controls and not like ASP.net Controls.
EDIT:
Note: The Project type should be Website, not a web Application. Web application won't support on demand compilation where website yes, it is.
If I understood currectly, you want to take the Markup from User which contains even asp.net controls and scriplets too.
if this is the case, Follow below steps:
Create a dummy .ascx control file, like DynamicMarkup.ascx with empty content
Add this user control to the page (xxxx.aspx) where you want to show this control statically so it registered to the page
<%# Register src="~/DynamicMarkup.ascx"
tagname="DynamicMarkup" tagprefix="MyASP" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server"
ID="DynamicMarkupContainer" ></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Write user input markup (may be get from database based on your criteria) to the DynamicMarkup.ascx file in page OnInit of the page (xxxx.aspx) And the create object of this DynamicMarkup
DynamicMarkup dynamicMarkup = LoadControl("~/DynamicMarkup.ascx") as
DynamicMarkup;
DynamicMarkupContainer.Controls.Add(ucSimpleControl);
I have not tested this approach, Just give a thought, With this you may get some session overwriting issue which you need handle.
Hope this will help!!
OLD:
is this the one that you are expecting? TextBox, and Button controls are available in System.Web.UI.WebControls namespace.
void Page_Load(Object sender, EventArgs e)
{
TextBox input = new TextBox();
input.Id ="input";
this.PlaceHolder.Controls.Add(input);
Button btnSend=new Button();
btnSend.Id ="btnSend";
btnSend.Text="Send";
btnSend.Click += new EventHandler(btnSend_Click);
this.PlaceHolder.Controls.Add(btnSend);
}
void btnSend_Click(object sender, EventArgs e)
{
// throw new NotImplementedException();
}
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="phHolder" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
code behind :
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Init()
{
GenerateContorls();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void GenerateContorls()
{
TextBox newTxt = new TextBox() { ID = "txtsend" };
Button newBtn = new Button() { Text = "Send", ID = "btnsend" };
newBtn.Click += btnsend_Click;
phHolder.Controls.Add(newTxt);
phHolder.Controls.Add(newBtn);
}
protected void btnsend_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)this.FindControl("txtsend");
//your code
}
}
hope it helps
I want to add a hidden field programmatically to an asp.net page, read and change it via javascript. So far my code fails at reading the added hidden field.
Here is a simple example:
Default.aspx:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<input type="hidden" id="myHiddenField1" value="blub" runat="server" />
<button onclick="myFunction()">click me</button>
<script>
function myFunction() {
var testVar = document.getElementById("myHiddenField1").value; //works: field defined in aspx page
var testVar2 = document.getElementById("myHiddenField2").value; //fails, Object required: field defined in codebehind
alert(testVar);
}
</script>
</body>
</html>
Default.aspx.cs (includes ommited):
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Page.RegisterHiddenField( "myHiddenField2", "bla!" ); doesnt work either
Page.ClientScript.RegisterHiddenField( "myHiddenField2", "bla" );
}
}
[edit]
The error i receive is: Microsoft JScript runtime error: Object required. If i add an alert(testVar2) and ignore the error the message box displays "undefined".
[/edit]
[edit2]
[removed edit, since i was wrong]
[/edit2]
Summering up my question: How do i create a hidden field in codebehind so i can get and set it from javascript?
You could try something like this:
protected void Page_Load(object sender, EventArgs e)
{
HtmlInputHidden hidden2 = new HtmlInputHidden();
hidden2.ID = "Here you will put the id of the control";
hidden2.Value = "Here you will put your value";
this.Controls.Add(hidden2);
}
At the top of your source code file, you have to add this statement:
using System.Web.UI.HtmlControls;
The main problem was that the following line was missing in the aspx page:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
The codebehind was never executed.
I am using WebForms and I am trying to perform Model Validation inside a Master-Page and for some reason the model is not picking up the values, meaning that after the validation fires if I enter a good value, the model keeps coming back empty hence triggering the validation over and over. If I put the code in page without Master-Page it works fine. I was able to put a very simple example and honestly, it's hard to believe that as common as MasterPages are, nobody has ran into this scenario so far. For the purpose of this example I embedded the Model in the Code Behind but having outside makes no different. Any idea will be greatly welcome. Thanks.
--Master-Page--
<%# Master Language="C#" AutoEventWireup="true" CodeFile="test.master.cs" Inherits="test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
-- WebForm --
<%# Page Title="" Language="C#" MasterPageFile="~/test.master" AutoEventWireup="true" CodeFile="test3.aspx.cs" Inherits="test3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<asp:ValidationSummary ID="valSummary" runat="server" />
</div>
<div><label>First Name:</label></div>
<div><input type="text" id="FirstName" runat="server" /></div>
<div><label>Middle Name:</label></div>
<div><input type="text" id="MiddleName" runat="server" /></div>
<div><label>Last Name:</label></div>
<div><input type="text" id="LastName" runat="server" /></div>
<div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
</asp:Content>
-- Code Behind --
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.ModelBinding;
using System.ComponentModel.DataAnnotations;
public partial class test3 : System.Web.UI.Page
{
public class testClass2
{
[Required()]
[MinLength(2)]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required()]
[MinLength(2)]
public string LastName { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
testClass2 tc = new testClass2();
if (TryUpdateModel(tc, new FormValueProvider(ModelBindingExecutionContext)))
{
System.Diagnostics.Debug.WriteLine("test");
}
}
}
}
The problem is indeed caused by usage of the master page. When used outside of the data bound control (such as GridView, FormView, Menu, etc.), FormValueProvider expects to have the same keys in Request.Form dictionary as property names in model object.
If you will take a closer look at generated HTML you will see that all input tags in form with master page have name attribute value set to something like ctl00$ContentPlaceHolder1$FirstName, ctl00$ContentPlaceHolder1$LastName, etc. while form without master page leaves name attribute intact and equal to the value of control's ID property.
This is the way of how UniqueID is generated to avoid name duplication (which should be avoided because in Web Forms we can have only one form tag and thus have controls with same ID's both on master page and form page).
And this is the cause why FormValueProvider cannot get values for your testClass2 object, it just cannot find FirstName, LastName, MiddleName values in posted form.
I found a solution.You can write a little front-end code to set the name equal to id and don't forget to set ClientIDMode to Static
<script>
$("input[type=text]").each(function () {
var id = $(this).attr("id");
$(this).attr("name", id);
});
</script>
I need a value from javascript before the main page load and then want to use that value in code. The code which I am using for that purpose is:
I have make a test.aspx page. The code for which is as following:-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title> <script type="text/javascript" language="javascript">
function GetScreenHeightAndWidth()
{
var width = screen.width;
var height = screen.height;
var object = 'Label1';
document.getElementById(object ).innerHTML=height ;
//alert(height);
'<%Session["Screensize"] = "' + height +'"; %>' ;
}
</script>
</head>
<body onload="GetScreenHeightAndWidth();" >
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="test"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
The code for test.aspx.cs page is as following:-
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Windows.Forms;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["Screensize"] = Label1.Text;
TextBox1.Text=Session["Screensize"].ToString();
}
}
The result is as following:-
768 test
while result what I need is 768 and 768.
Is there any way to solve the problem?
What you are asking is impossible to do. Why do you need to know the screen size on the server -side in the first place? Whatever you need to accommodate on the html produced by the server can be either adjusted via proper CSS rules or Javascript (JQuery if you prefer that framework)
If you set the width/height values to a hidden field from script, you can than access them from codebehind after a postback. Labels are not posted with the form so you cant use that.
First of all thanks to all of you for responding to my question. After much search I have found what I was exactly wanting. For this I have to use one more page and add this code in my original code:
if (!IsPostBack)
{
if (Session["ScreenResolution"] == null)
{
Response.Redirect("detectscreen.aspx");
}
else
{
Session["Screensize"] = Session["ScreenResolution"].ToString();
}
TextBox1.Text = Session["Screensize"].ToString();
}
And the code for new page is:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["action"] != null) {
Session["ScreenResolution"] = Request.QueryString["res"].ToString();
Response.Redirect("Catalogue.aspx");
}
}
and the script in the new page will be like this:
<script language="javascript" type="text/javascript">
res = "&res="+screen.height
top.location.href="detectscreen.aspx?action=set"+res
</script>
I am using FileUpload Control to upload images, I can select the image using that browse button, but when i try to preview that selected one, i am not getting the file name, its showing empty..
protected void btnImgUpload_Click(object sender, ImageClickEventArgs e)
{
try
{
string strimage;
string strfilename, strextn;
if (fupImage.HasFile)
{
In the above code,fupImage.FileName property should have to selected Image name, but it remains as empty string "" , so fubImage.HasFile condition is going false. I am not getting why the condition is going false, while the file is selected,? what is the problem here?
Thanks in advance
what i did to test it is
I create an Asp page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fupImage" runat="server" />
<asp:Button ID="btnImageUpload" runat="server" onclick="btnImageUpload_Click"
Text="Upload" />
</div>
</form>
</body>
</html>
and the code behind class is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnImageUpload_Click(object sender, EventArgs e)
{
try
{
string strimage;
string strfilename, strextn;
if (fupImage.HasFile)
{
//do something
}
}
catch
{
}
}
}
}
and nothing goes wrong with that
I want to say to test it just create a very simple instance and test it in complex environment may be there are some extra rules may prevents normal jobs! and sometimes it looks so unnoraml
Check for the View-state property of that file uploader Control, If View-state is false, then on post back you'll get empty value