I try to upload a file in a form in ASP.NET, my form is
<form metod="post" asp-controller="Home" asp-action="FormPage">
<input type="text" asp-for="Name" />
<input type="file" asp-for="Image" accept="image/*" />
</form>
and the model is:
class MyCLass {
public int Id { get; set; }
public string Name { get; set; }
public byte[] Image { get; set }
}
but when I select a file for the image-input, I get that it is not a valid input when i submit. Are there ways to solve it?
But, why do you care how or what the file being up-loaded is?
I mean, with any simple fileupload control, once the post-back has occured, you have the "in memory" file, and you are 100% free to convert to a byte() array at that point time. Why even bother or have the client side have to do any of that mumbo jumbo anyway?
I mean this:
<h3>Select file to up-load</h3>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="cmdGO" runat="server" Text="Up-load"
OnClick="cmdGO_Click" />
And then code behind:
protected void cmdGO_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
byte[] FileAsBytes;
FileAsBytes = (byte[])FileUpload1.FileBytes;
// do whatever with the byte array
MyCLass cFile = new MyCLass();
cFile.Id = 134;
cFile.Name = "Hello";
cFile.Image = FileAsBytes;
}
}
or probably better yet:
protected void cmdGO_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// do whatever with the byte array
MyCLass cFile = new MyCLass();
cFile.Id = 134;
cFile.Name = "Hello";
cFile.Image = (byte[])FileUpload1.FileBytes;
// do whatever
}
}
So, you can easy convert the file to bytes[] in the server side code.
Related
I am not able to read the Checked status of my custom checkbox control.
I created this control so that it would rendor correctly for easy use with bootstrap.
The control renders perfectly, and I have all the function that I want/need EXCEPT being able to read the checked status of the input when the user clicks 'submit'.
Custom Server Control Code (C#):
public class InlineBootstrapCheckBox : CheckBox, IPostBackDataHandler, ICheckBoxControl
{
private string value;
private string labelCSS;
private string labelID;
public string LabelID
{
get
{
if (!string.IsNullOrEmpty(this.labelID))
{
return this.labelID;
}
else
{
return null;
}
}
set
{
this.labelID = value;
}
}
public string LabelCSS
{
get
{
if (!string.IsNullOrEmpty(this.labelCSS))
{
return this.labelCSS;
}
else
{
return null;
}
}
set
{
this.labelCSS = value;
}
}
public string Value
{
get
{
if (!string.IsNullOrEmpty(this.value))
{
return this.value;
}
else
{
throw new NotImplementedException("You must set a 'Value' for InlineBootstrapCheckBox Controls");
}
}
set
{
this.value = value;
}
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.WriteLine(string.Format("<label id=\"{0}\" class=\"{1}\" for=\"{2}\">", (this.LabelID != null) ? this.LabelID : string.Concat(this.ID, "_Label"), (this.LabelCSS != null) ? string.Concat(this.LabelCSS, " checkbox-inline") : "checkbox-inline", this.ID));
writer.WriteLine(string.Format("<input type=\"checkbox\" id=\"{0}\" value=\"{1}\">", this.ID, this.Value));
writer.WriteLine(this.Text);
writer.WriteLine("</label>");
}
}
Markup Code (.ASPX):
<div class="form-group">
<label id="lblCategories" class="col-sm-3 control-label">Categories</label>
<div class="col-sm-9">
<cookout:InlineBootstrapCheckBox runat="server" ID="chkRibs" Text="Ribs" Value="1" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkChicken" Text="Chicken" Value="2" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkBrisket" Text="Beef Brisket" Value="3" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkPork" Text="Pork" Value="4" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkAnythingBut" Text="Anything But" Value="5" />
</div>
</div>
Code Behind (C#):
This is where I think my problem is?
protected void btnSubmit_Click(object sender, EventArgs e)
{
ProRegistration regInfo = new ProRegistration();
regInfo.TeamName = this.txtTeamName.Text.ToString();
regInfo.ContactName = this.txtContactName.Text.ToString();
regInfo.StreetAddress = this.txtContactAddress.Text.ToString();
regInfo.City = this.txtContactCity.Text.ToString();
regInfo.State = this.txtContactState.Text.ToString();
regInfo.ZipCode = this.txtContactZip.Text.ToString();
regInfo.Email = this.txtContactEmail.Text.ToString();
regInfo.Phone = this.txtContactPhone.Text.ToString();
regInfo.IsRibs = this.chkRibs.Checked;
regInfo.IsChicken = this.chkChicken.Checked;
regInfo.IsBrisket = this.chkBrisket.Checked;
regInfo.IsPork = this.chkPork.Checked;
regInfo.IsAnythingBut = this.chkAnythingBut.Checked;
regInfo.Created = DateTime.Now;
DataManager.InsertProfessionalRegistration(regInfo);
}
...So basically what I need is to be able to get a positive response when I try to submit this object to my database. Currently, no matter the click status, I get a false result.
I have been trying to research an answer to this for about 3 hours now to no avail.
Thank you!
I don't know bootstrap but it looks like you are injecting an html checkbox into the output. If this is the case it will not be recognized as a server control on postback, however you can get its value by using the request.form object.
string result=Request.Form["thecheckboxid"];
I'm trying to make my first ASP.NET web site and am unable to get searching and paging to work in ASP.NET Web Forms without using an invisible button. I can't use my search button's click event because it needs to reset my page to 0 when clicked, so it only has a client-click event. I have to make it call a JavaScript function, which calls the invisible button's click event handler after doing so. The only way I can figure out around it is to make the page post back to itself and pass the index in from the bottom paging table. Hopefully, someone here might have some suggestions for an easier way to do it. Thanks in advance for any suggestions. If it wasn't for paging, it would be one line of code inside my button click event handler.
Here is the relevant markup for my page.
<script language="javascript">
function page(index)
{
document.getElementById('PageIndex').value = index;
document.getElementById('btnInvisible').click();
}
</script>
<uc1:ucWidgetSearch runat="server" id="ctl" />
<p id="pHTML" runat="server"/>
<asp:Button ID="btnInvisible" runat="server" BackColor="White"
BorderStyle="None" BorderWidth="0px" OnClick="btnInvisible_Click" />
<asp:HiddenField ID="PageIndex" runat="server" /
Here is the markup for the UserControl on the page.
<label>Last Name:</label>
<asp:TextBox ID="txtLastName" runat="server" MaxLength="50" Enabled="false"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClientClick="page('0')" />
Here is the C# code behind for the .aspx page. The .aspx page uses no using statements.
namespace Widgets.WebUI
{ public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{ ScreenHelper.LoadScreen(ctl.Search(), pHTML, PageIndex);}
protected void btnInvisible_Click(object sender, System.EventArgs e)
{ }
}
}
Here is the code behind for the UserControl. It also uses no using statements.
public partial class ucWidgetSearch : System.Web.UI.UserControl
{
internal Widgets.BLL.WidgetSearch Search()
{
if (!txtLastName.Enabled)
{
txtLastName.Enabled = true;
txtLastName.Focus();
return null;
}
return new Widgets.BLL.WidgetSearch(txtLastName.Text);
}
}
Finally, there is a ScreenHelper class that calls into the BLL layer, which calls into the DAL layer and constructs an HTML document and passes it into the p element on the main page.
internal class ScreenHelper
{
internal static void LoadScreen(WidgetSearch search,
System.Web.UI.HtmlControls.HtmlGenericControl p, HiddenField page)
{
if (search != null)
{
try
{
p.InnerHtml = WidgetsLogic.GetHTMLTable(search.LastName, int.Parse(page.Value), 20);
}
catch (System.Exception ex)
{
p.InnerHtml = "<label style=\"color: #FF0000\">Error loading screen: " + ex.Message + "</label>";
}
}
}
}
namespace Widgets.BLL
{
public class WidgetsLogic
{
public static string GetHTMLTable(string name, int pageIndex, int? pageSize)
{
StringBuilder strBuilder = new StringBuilder("<table border=\"1\">");
List<Widget> list = WidgetsDataAccess.GetByName(name);
int minDex = 0, maxDex = list.Count;
if (pageSize == null)
{
pageIndex = 0;
}
else
{
pageIndex = HTMLHelper.GetPageIndex(pageIndex, pageSize.Value, list.Count);
minDex = pageIndex * pageSize.Value;
maxDex = minDex + pageSize.Value;
if (maxDex > list.Count)
maxDex = list.Count;
}
for (int i = minDex; i < maxDex; i++)
{
strBuilder.Append("<tr");
// Set Light Gray Color for alterating rows in table
if (i%2 != 0)
strBuilder.Append(" style=\"background-color: #EBEBEB\"");
strBuilder.Append("><td>" + list[i].ID.ToString() + "</td>");
strBuilder.Append("<td>" + list[i].Name + "</td></tr>");
}
strBuilder.Append("</table>");
// Add Paging if appropriate
if (pageSize != null && pageSize.Value < list.Count)
{
strBuilder.Append(HTMLHelper.GetPagingFooter(pageIndex, pageSize.Value,
list.Count, "javascript:page('#pageIndex')"));
}
string str = strBuilder.ToString();
return str;
}
}
you should never try to do paging manually. Rather use GridView and an ObjectDataSource
to bind data to your page. This way ASP.NET handles the pageIndex exc via viewstate and the ObjectDatasource handles paging for you.Check this link for a good example of how to do just that.
Use ClientID to refer to the actual ID of an HTML control
document.getElementById('<%= PageIndex.ClientID %>').value = index;
I am not getting this Modal window / javascript stuff , I’m a bit of a noob I ve found tons of stuff about this trawling around
But its hard to find the answer when you lack the experience to ask the correct question.
and are not up to speed with all the jargon either
System.windows.froms.messagebox doesn’t work in a web situation.. I’ve discovered that much,,, This is an intranet application
How do I evaluate the result of the javascript function OpenDialogue() in a similar way to declaring DialogResult myVar =
I have a button event handler like this
protected void but_Comds(object sender, EventArgs e)
{
GridViewRow row = results.SelectedRow;
string crn = Convert.ToString(row.Cells[13].Text);
if (sender == but_crn)
{
checkData(row, crn);
}
}
Then some methods
private void checkData(GridViewRow row, string crn)
{
if (stuff)
{
DialogResult checkCrn = System.Windows.Forms.MessageBox.Show("a mesage",
"Data Check",
MessageBoxButtons.YesNoCancel);
if (checkCrn == DialogResult.No)
{
Do stuff;
}
if (checkCrn == DialogResult.Cancel)
{
Do other stuff;
}
}
else
{
Do stuff instead
}
}
I can get the dialogue to run easy enough as a child page but I can’t work out capture the return value from the child page.
I have been trying to wrap it into a method amongst other things
And I can see this doesn’t work because ClientScript.RegisterStartupScript Is void.
protected string MsgDialogue()
{
Return ClientScript.RegisterStartupScript(this.GetType(),
"newWindow", String.Format("<script>OpenDialog();</script>"));
}
I have also tried okClicked(object sender, eventargs e) methods in the childs code behind
And tried to write a variable into the MySession class and then get that variable in the checkData (row, crn) method
There must be some simple more elegant way of doing this without having to trawl thousands of pages
Hoping to stumble on it..
Here is my javascript on the mainpage
<script type="text/javascript">
function OpenDialog() {
// get the control values
var str1 = 'test';
// create an array with the values
var winArgs = new Array(str1);
var winSettings = 'center:yes;resizable:no;help:no;status:no;dialogWidth:250px;dialogHeight:200px';
// return the dialog control values after passing them as a parameter
winArgs = window.showModalDialog('child.aspx', winArgs, winSettings);
// see if the array is null
if (winArgs == null) {
window.alert('no data returned!');
}
return winArgs;
}
</script>
Here is child.aspx
<head runat="server">
<title></title>
<base target="_self"/>
<script type="text/javascript">
function GetData() {
// intialize variables and array to empty
var str1 = '';
var winArgs = new Array(str1);
// get the values as arguments and set the controls
winArgs = window.dialogArguments;
document.getElementById('TextBox1').value = winArgs[0];
}
function but_ok() {
window.returnValue = "ok";
window.close();
}
function but_cancel() {
window.returnValue = "cancel";
window.close();
}
function but_yes() {
window.returnValue = "yes";
window.close();
}
function but_no() {
window.returnValue = "no";
window.close();
}
</script>
</head>
<body onload="GetData()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly ="true"></asp:TextBox>
<asp:Button ID="dlg_ok" runat="server" Text=" OK " />
<asp:Button ID="dlg_cancel" runat="server" Text=" Cancel " />
<asp:Button ID="dlg_yes" runat="server" Text=" Yes " />
<asp:Button ID="dlg_no" runat="server" Text=" No " />
</div>
</form>
</body>
</html>
And child.aspx. cs
public class child : System.Web.UI.Page
{
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
protected global::System.Web.UI.WebControls.TextBox TextBox1;
protected global::System.Web.UI.WebControls.Button dlg_ok;
protected global::System.Web.UI.WebControls.Button dlg_cancel;
protected global::System.Web.UI.WebControls.Button dlg_yes;
protected global::System.Web.UI.WebControls.Button dlg_no;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dlg_ok.Attributes["onclick"] = "javascript:but_ok()";
dlg_cancel.Attributes["onclick"] = "javascript:but_cancel()";
dlg_yes.Attributes["onclick"] = "javascript:but_yes()";
dlg_no.Attributes["onclick"] = "javascript:but_no()";
}
}
}
Sorry ive posted quite a bit of code but hopefully if you can see what I’m trying to do
Then you might be able to better explain what I’m not getting.
I have very simple website (http://mysite.com), that contains one page, that page generates random datetime value and writes it to lable, code of that page is:
<form id="form1" runat="server">
<div>
<asp:Label ID="lblGeneratedDateTime" runat="server"></asp:Label>
<br />
<asp:DropDownList ID="ddlGenerateDateTime" runat="server" AutoPostBack="true"
onselectedindexchanged="ddlGenerateDateTime_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="0">Today</asp:ListItem>
<asp:ListItem Value="1">-1 day</asp:ListItem>
<asp:ListItem Value="2">-2 days</asp:ListItem>
</asp:DropDownList>
</div>
</form>
and C# code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblGeneratedDateTime.Text = GenerateDateTime(0).ToString();
}
}
protected void ddlGenerateDateTime_SelectedIndexChanged(object sender, EventArgs e)
{
int value = Convert.ToInt32(ddlGenerateDateTime.SelectedValue);
lblGeneratedDateTime.Text = GenerateDateTime(value).ToString();
}
Random random = new Random();
private DateTime GenerateDateTime(int minusDays)
{
DateTime date = DateTime.Now.AddDays(-minusDays);
return new DateTime(date.Year, date.Month, date.Day,
random.Next(0, 23), random.Next(0, 59), random.Next(0, 59));
}
}
Now, from WinForm App I need READ generated time on the page, so for default value I do:
string url = "http://mysite.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string page = streamReader.ReadToEnd();
int start = str.IndexOf("lblGeneratedDateTime\">") + 22;
int end = str.LastIndexOf("</span>");
string generatedDateTime = str.Substring(start, end - start);
return generatedDateTime;
How can I read generated values (page content) for -1 and -2 days which needs do postback of DropDownList. Or it's impossible?
Thanks for any reply!
Added. Code of the site I can't change!
You can't do this like that... you download the html response as a string, so it's impossible to interact with the page and simulate a dropdown change..
You can try using WebClient and submit the form page with different value for you dropdown.. this will generate different responses that you can parse with your code above.
It needs to use WebBrowser instead.
WebBrowser wb = new WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
string url = "http://mysite.com";
wb.Navigate(url);
HtmlElement item = wb.Document.GetElementById("ddlGenerateDateTime");
then
item.SetAttribute("value", "1");
item.InvokeMember("onchange");
item.SetAttribute("value", "2");
item.InvokeMember("onchange");
in that case it's possible to send postback to page.
I'm trying to make a generic Search UserControl that can be given some values, based on those values the search results will display. However I'm currently trying to display the results of my values, and they always show up as my default values.
my UserControl code:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ProductSearch.ascx.cs" Inherits="..." %>
<asp:Label ID="lblSearchWord" runat="server" />
<asp:Label ID="lblSearch" runat="server" />
Code Behind:
private string _searchWord = string.Empty;
private int _search = -1;
public string SearchWord
{
get { return _searchWord; }
set { _searchWord = value; }
}
public int Search
{
get { return _search; }
set { _search = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
lblGroupId.Text = LevelId.ToString();
lblSearchWord.Text = SearchWord;
}
When I press the search button on the main aspx.cs page I do the following:
protected void btnSearch_Click(object sender, EventArgs e)
{
ucPS.SearchWord = txtProductSearch.Text;
ucPS.Search = 1
}
My aspx page contains the following
<%# Register src="UserControls/ProductSearch.ascx" tagname="ProductSearch" tagprefix="ps" %>
<ps:ProductSearch id="ucPS" runat="server" />
My problem is that I can't use Query strings as the user might have selected some other things on this page that I need to keep the state of, however I did test that one and foudn it working.
Where am I going wrong? or is there an better alternative (except for query strings).
All variables in a page are disposed at the end of the page-lifecycle. Hence SearchWord will always be initialized with the default value on every postback.
You need to persist it somewehere else, for example in a ViewState variable.
public string SearchWord
{
get
{
if (ViewState["SearchWord"] == null)
return "";
else
return (String)ViewState["SearchWord"];
}
set { ViewState["SearchWord"] = value; }
}
Nine Options for Managing Persistent User State in Your ASP.NET Application
public string SearchWord
{
get
{
if (ViewState["SearchWord"] == null)
ViewState["SearchWord"] = string.Empty;
return ViewState["SearchWord"];
}
set
{
ViewState["SearchWord"] = value;
}
}
and I use databind not pageload, this way your usercontrol doesn't load unless you call it.
protected override DataBind()
{
//you can add a condition here if you like
if(SearchWord != string.Empty)
lblSearchWord.Text = SearchWord;
}
to call this from aspx:
usercontrol.SearchWord = "my word";
usercontrol.DataBind();
and thats it..