I have a problem with my webapplication. I have made an upload-function for uploading documents. one For Answer Paper And Another Is Question Paper. I have No problem In Question Papeer Its Works Fine But When After Upload Answer Paper is Corrupt..
Any Idia
<div >
<label class="control-label" for="fileInput">Attached Question File </label>
<div class="controls">
<asp:FileUpload ID="fuQFile" runat="server" onChange="chngFUvalue(this)" CssClass="input-file uniform_on" />
<asp:Label ID="lblQVfile" runat="server" Text=""></asp:Label></div>
</div>
<div class="control-group">
<label class="control-label" for="fileInput">Attached Answer File </label>
<div class="controls">
<asp:FileUpload ID="fuAFile" runat="server" onChange="chngFUvalue(this)" CssClass="input-file uniform_on" />
<asp:Label ID="lblAVfile" runat="server" Text=""></asp:Label></div>
</div>
///For Question Pappr(Works Fine)////
string VQFile = "", VQFilePath = "";
if (fuQFile.HasFile)
{
VQFile = fuQFile.FileName.ToString();
VQFilePath = "1upload/files/Question/" + VQFile;
fuQFile.SaveAs(Server.MapPath("~/1upload/files/Question/") + VQFile);
}
else
{
VQFilePath = lblQVfile.Text;
}
// For Answer Paper(Facing Problem With That Part)////File Is Corrupt After Upload//////
if (fuAFile.HasFile)
{
VAFile = rndnom + "-" + fuAFile.FileName.ToString();
VAFilePath = "1upload/files/Answer/" + VAFile;
fuQFile.SaveAs(Server.MapPath("~/1upload/files/Answer/") + VAFile);
}
else
{
VAFilePath = lblAVfile.Text;
}
Your are calling fuQFile.SaveAs when saving the answer file, rather than fuAFile.SaveAs.
Related
I have bootstrap modal popup that pops up to enable user to select images to upload, So when the user chooses images I have javascript function that add new <div> containing the filename, then the user click save to save the images on the database, every thing is working except the input file is caching the old images and uploading them again with the newly selected images.
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="functionalUpdatePanel">
<ContentTemplate>
<button title="إضافة مرفق" data-toggle="modal" class="uploadAttach" data-target="#myModal" ></button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-
labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true"> </button>
<h4 class="modal-title" id="myModalLabel">إضافة مرفق</h4>
</div>
<div class="modal-body">
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" />
<h5 style="margin-right:45%;font-weight:bold;font-
size:1.2em">اختر المرفق</h5>
<div class="uploadBtnDiv">
<input
style="cursor:pointer;opacity:0;width:100%;height:100%"
title="اختيار مرفق" type="file" id="myFile" name="myFile"
multiple="multiple" />
</div>
<br />
<br />
</div>
<div class="modal-footer">
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button style="width:100%
!important;" Text="حفظ" title="إرسال المرفق" CssClass="btn
btn-success" runat="server" ID="btnUpload"
OnClick="btnUploadClick" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger
ControlID="btnUpload" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
and here is my java script function
$(document).on('change', '#myFile:visible', function() {
var files = $(this)[0].files;
var newLine;
for (var i = 0; i < files.length; i++) {
newLine = "<div class='attach-line'>" +
"<div class='attach-name'>" +
files[i].name.slice(0,25)+'...' +
"<i class='icon-trash remove attach-delete'></i>" +
"</div>" +
"<br/>"+
"</div>";
$("#myModal .modal-body").append(newLine);
// Clone the file selector, assign the name, hide and append it
$(this).clone().hide().attr('name', 'myFile[]').insertAfter($(this));
}
$(".remove").click(function(){
$(this).parent(".attach-name").remove();
});
});
and bellow is the code behind
protected void btnUploadClick(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("AppId", typeof(int));
dt.Columns.Add("Bytes", typeof(byte[]));
dt.Columns.Add("ImgNames", typeof(string));
dt.Columns.Add("ImgType", typeof(string));
dt.Columns.Add("DedicatedMemberId", typeof(int));
for (int i = 0; i < Request.Files.Count; i++)
{
if (Request.Files[i] != null && Request.Files[i].ContentLength > 0)
{
string fType = Request.Files[i].ContentType.Split('/')[1];
string fName = Path.GetFileName(Request.Files[i].FileName);
byte[] bytes = new BinaryReader(Request.Files[i].InputStream).ReadBytes(Request.Files[i].ContentLength);
dt.Rows.Add(Convert.ToInt32(hfAppId.Value), bytes, fName,
fType, Convert.ToInt32(ViewState["memberId"]));
}
}
string outputStr = AppsOperations.UpdateAttach("إرفاق صورة جديدة", "الطلبات ", dt, User.Identity.Name);
if (outputStr == "s")
{
string redirectStr = "AuditApp.aspx?seq=" + hfAttSeq.Value + "&&AppType=" + hfAppType.Value + "&&id=" + hfAppId.Value;
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('تم تحميل المرفق بنجاح');window.location='" + redirectStr + "';", true);
}
else if (outputStr == "f")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + "تعذر تحميل المرفق" + "')", true);
}
}
i am able to find the answer, actually i use the same code in another page to cache images for the use so i removed this the bellow line from java script function
$(this).clone().hide().attr('name', 'myFile[]').insertAfter($(this));
Just for background: So Im trying to create an interface for users to check-in. The concept is simple:A Listview where each item holds an image, name, some info, and a button to the right that says check-in (That they'd press).
This interface is on a webpage (.aspx) with an .aspx.cs codefile.
I've created my ListView & set templates
<asp:ListView
ID="lvInstructors"
runat="server"
AutoGenerateColumns="False"
ShowRegularGridWhenEmpty="False"
EmptyDataText="No Sessions to Display."
OnRowDataBound="lvDataBound"
OnRowCommand="lvCommand"
Visible="true">
<LayoutTemplate>
<div class="container" id="mainContent">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div class="row instructorItem">
<div class="col-2 sessionStartTimeDiv">
<p class="sessionStartTime"></p>
</div>
<div class="col-2 instructorHeadshotDiv">
<asp:Image class="instructorHeadshot" runat="server" src="" />
</div>
<div class="col-5 sessionInfoDiv">
<h3 class="instructorName"></h3>
<p class="sessionInfo"></p>
</div>
<div class="col-3 checkInBtnDiv">
<asp:Button class="checkInBtn" OnClick="CheckInBtn_Click" ID="checkInBtn" runat="server" Text="CHECK-IN" />
</div>
</div>
</ItemTemplate>
<EmptyDataTemplate>No Sessions to Display</EmptyDataTemplate>
</asp:ListView>
My issue is, I don't want to link this ListView to a database, source, or table (Is that even possible)
Below are the variables in .aspx.cs that I'd like to populate my ListView Items with, but Im not sure how to go about doing do, especially when it comes to creating a new ListView Item per each for loop. Any suggestions? Thanks Alot!
foreach (Session S in UpcomingSessions)
{
foreach(Enrollment I in S.Instructors())
{
SessionName = S.Name;
SessionStartTime = S.FirstDateTime().ToShortTimeString();
InstructorName = I.FirstName + " " + I.LastName;
SessionRoom = S.Room.ToString();
}
}
Try like this
public class Instructors{
public string SessionName{get;set;}
public DateTime SessionStartTime {get;set;}
public string InstructorName {get;set;}
public string SessionRoom {get;set;}
}
List<Instructors> InstructorsLst=new List<Instructors>();
foreach (Session S in UpcomingSessions)
{
foreach(Enrollment I in S.Instructors())
{
Instructors inst=new Instructors();
inst.SessionName = S.Name;
inst.SessionStartTime = S.FirstDateTime().ToShortTimeString();
inst.InstructorName = I.FirstName + " " + I.LastName;
inst.SessionRoom = S.Room.ToString();
InstructorsLst.Add(inst);
}
}
lvInstructors.DataSrouce = InstructorsLst;
lvInstructors.DataBind();
I'm having problems with a chunk of code that's meant to add a textbox to a Repeater in ASP.
I have the following:
<asp:Repeater ID="uxRolesList" runat="server">
<ItemTemplate>
<div id="<%# GetRolesDivId() %>" class="div_row">
<asp:TextBox ID="uxTxtBoxRole" runat="server" rows="5" columns="100" Text='<%# DataBinder.Eval(Container.DataItem, "RequirementDescription") %>' TextMode="multiline" MaxLength="2000"></asp:TextBox>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" />
<br /><br />
</div>
</ItemTemplate>
</asp:Repeater>
Which generates a load of textboxes that look like this in the html:
<td id="rolesColumn">
<div id="roles-0" class="div_row">
<textarea name="ctl00$mainContent$uxRolesList$ctl00$uxTxtBoxRole" rows="5" cols="100" id="ctl00_mainContent_uxRolesList_ctl00_uxTxtBoxRole">Cool Job1</textarea>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" />
<br /><br />
</div>
</td>
I've also added the following button, that should add a textbox to this list when hit:
<asp:Button CssClass="btn" ID="uxAddRoleBtn" runat="server" Text="Add a new role requirement" />
Using the following jQuery code:
$("#ctl00_mainContent_uxAddRoleBtn").live("click", (function (e) {
var rolesCounter = $('#ctl00_mainContent_uxTxtBoxRolesCount').val();
if (rolesCounter < 10) {
var rolesCounterText = "0" + rolesCounter;
} else {
var rolesCounterText = rolesCounter;
}
$('#rolesColumn').append("<div id='roles-" + rolesCounter + "' class='div_row'><textarea name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "$uxTxtBoxRole' rows='5' cols='100' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxTxtBoxRole' MaxLength='2000' ></textarea><input type='submit' name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "$uxRemoveRoleBtn' value='X' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxRemoveRoleBtn' class='remove-roles-btn' style='vertical-align:top;' /><br /><span id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxValTxtBoxRole' style='color:Red;visibility:hidden;'>Please complete this role requirement</span><br /><br /></div>");
e.preventDefault();
rolesCounter++;
$('#ctl00_mainContent_uxTxtBoxRolesCount').val(rolesCounter);
}));
So far so good. I hit the add button and the textbox appears, I type something in, everything's great. The html look something like this:
<div id="roles-0" class="div_row">
<textarea id="ctl00_mainContent_uxRolesList_ctl00_uxTxtBoxRole" cols="100" rows="5" name="ctl00$mainContent$uxRolesList$ctl00$uxTxtBoxRole">Cool Job1</textarea><input class="remove-roles-btn" type="button" value="X" style="vertical-align:top;"><br><br>
</div>
<div id="roles-1" class="div_row">
<textarea id="ctl00_mainContent_uxRolesList_ctl01_uxTxtBoxRole" maxlength="2000" cols="100" rows="5" name="ctl00$mainContent$uxRolesList$ctl01$uxTxtBoxRole">Test</textarea><input class="remove-roles-btn" type="submit" style="vertical-align:top;" value="X" name="ctl00$mainContent$uxRolesList$ctl01$uxRemoveRoleBtn"><br><br>
</div>
Then I hit submit and the new values do not come through.
In the C# side I'm trying to access the data using:
foreach (RepeaterItem item in dl.Items)
{
System.Web.UI.WebControls.TextBox rb = item.FindControl(control) as System.Web.UI.WebControls.TextBox;
if (rb.Text.Trim() != "")
{
PositionRequirement pr = new PositionRequirement();
pr.RequirementDescription = rb.Text;
pr.RequirementLevel = new PositionRequirementLevel(level, levelDescription);
pr.OrderNumber = i;
i++;
positionRequirements.Add(pr);
}
}
where dl = uxRolesList
control = uxTxtBoxRole
I'm at an utter loss as to why the new values are not coming through with the uxRolesList Repeater.
What am I doing wrong?
from what i know , the approach used is not going to show the items that are added within the Repeater Datasource, unless they exist before the page is being served to the user, so in the example, only the items that were bound to the repeater before leaving the server (if any) will show.
if you don't want to leave the page and make a trip to the server on every add click,of the top my head i would suggest that you would access them via the request Object using the name instead of the id ( Request[""] ) and keep the name of each textbox similar ("txtbox1","txtbox2")and append the count as you did in your Jquery code, then on the server when the page is submitted loop over the items using the counter that you have stored in uxTxtBoxRolesCount.
I am creating a survey, it has 60 textboxes I need to require that at least 40 of these textboxes are filled in upon hitting the submit button, it doesn't matter which ones as long as 40 have text within them. Any ideas how to accomplish this with C# or maybe another way?
A few of my textboxes:
<div class="row">
<div class="span3">
<div class="control-group">
<asp:Label ID="SupperLbl" class="control-label required" runat="server" Text="Best Supper Club"></asp:Label>
<div class="controls">
<asp:TextBox ID="SupperTxtBox" class="span3" runat="server"></asp:TextBox>
</div>
</div>
</div>
<div class="span3">
<div class="control-group">
<asp:Label ID="YogurtLbl" class="control-label required" runat="server" Text="Best Place for Frozen Yogurt"></asp:Label>
<div class="controls">
<asp:TextBox ID="YogurtTxtBox" class="span3" runat="server"></asp:TextBox>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span3">
<div class="control-group">
<asp:Label ID="Label1" class="control-label required" runat="server" Text="Best Place for Dessert"></asp:Label>
<div class="controls">
<asp:TextBox ID="DessertTxtBox" class="span3" runat="server"></asp:TextBox>
</div>
</div>
</div>
<div class="span3">
<div class="control-group">
<asp:Label ID="Label2" class="control-label required" runat="server" Text="Best Place for Chicken"></asp:Label>
<div class="controls">
<asp:TextBox ID="ChickenTxtBox" class="span3" runat="server"></asp:TextBox>
</div>
</div>
</div>
</div>
.....
Place your textboxes in an array, then do some validation.
//Place textboxes in array for easy access
TextBox[] validatedTexboxes = new TextBox[] {
textbox1, textbox2, textbox3, ...
};
//On submit, make sure 40 are filled in.
var filledTextboxes = validatedTexboxes.Count(x => !String.IsNullOrWhiteSpace(x.Text));
if (filledTextboxes > 40)
//Do Something
string[] txtArr = { "SupperTxtBox", "YogurtTxtBox", "DessertTxtBox" };
protected void Page_Load(object sender, EventArgs e)
{
string[] lblArr = { "Best Supper Club", "Best Place for Frozen Yogurt", "Best Place for Dessert" };
for (int i = 0; i < lblArr.Length; i++)
{
Label lbl = new Label();
lbl.Text = "<br>" + lblArr[i] + "<br>";
TextBox txt = new TextBox();
txt.ID = txtArr[i];
Form.Controls.Add(lbl);
Form.Controls.Add(txt);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int Count = 0;
foreach (string item in txtArr)
{
TextBox t = (TextBox)Form.FindControl(item);
if (t != null)
{
if (t.Text.Trim() != "")
Count++;
}
}
if (Count < 3)
{
Response.Write("<br>You fill " + Count + " textbox, Please fill 3 textbox!");
}
}
If you want the validation on the server side, you can loop recursively on all the controls of the page, take the textboxes and verify if at least 40 contains text.
For the recursive loop, you can use the extension method from this answer :
public static IEnumerable<T> FindControls<T>(this Control control, bool recurse) where T : Control
{
List<T> found = new List<T>();
Action<Control> search = null;
search = ctrl =>
{
foreach (Control child in ctrl.Controls)
{
if (typeof(T).IsAssignableFrom(child.GetType()))
{
found.Add((T)child);
}
if (recurse)
{
search(child);
}
}
};
search(control);
return found;
}
All you need to do now is get the array and verify that at least 40 of them contain text :
private bool AreAtLeast40TextBoxesFilled()
{
var allTextBoxes = this.Page.FindControls<TextBox>(true);
return allTextBoxes.Count(t => !string.IsNullOrWhiteSpace(t.Text)) >= 40;
}
Use Phil Haack's tutorials on MVC list model binding so you can keep track of the value and the id of the textbox in a list and then check the count on the server side.
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
If the total count of elements in the list is less than your limit than return a modelstate validation error and return the same view.
If you need a specific example let me know.
I need to write some code that places one of 3 choices of "blocks" of html in a specified place on the page. How can I do this?
I was thinking I can use single value databinding, but I don't think this is the correct way.
I'm using ASP.NET c#.
Edit: here is what it might look like:
MapPlaceholder.InnerHtml = #"<div class="mapContainer smallMap" id="smallGrid" runat="server" visible="false">
<div id="node1" class="gridBox" runat="server">
</div>
<div id="node2" class="gridBox" runat="server">
</div>
<div id="node3" class="gridBox" runat="server">
</div>
<div id="node4" class="gridBox" runat="server">
</div>
<div id="node5" class="gridBox" runat="server">
</div>
<div id="node6" class="gridBox" runat="server">
</div>
<div id="node7" class="gridBox" runat="server">
</div>
<div id="node8" class="gridBox" runat="server">
</div>
<div id="node9" class="gridBox" runat="server">
</div>
</div>";
and in the .aspx page:
<div id="MapPlaceholder" runat="server"></div>
One more thing, how can I tell C# to actually write the " in the string? It isnt working currently because it stop at the first " it finds.
Edit: I have another problem.
MapPlaceholder.InnerHtml = block1;
HtmlGenericControl smallGrid = (HtmlGenericControl)MapPlaceholder.FindControl("smallGrid");
containerName = "smallGrid";
smallGrid.Visible = true;
smallGrid.Attributes["Style"] = "background-image:url('" + du.getMapBackgroundImage(mapId) + "'); " + "width:300px; height:300px;";
containerName = "smallGrid";
This is what i am trying to do, but the FindControl always returns null. I debugged this and it seems that the html code is being added, but only after the pageload ends. Is there anyway i can tell c# to "render" the div so i can work with it like i need to?
To have double quotes in code, you need to have two of them when using # so it would be:
MapPlaceholder.InnerHtml = #"<div class=""mapContainer smallMap"" id=""smallGrid"" runat=""server"" visible=""false"">
<div id=""node1"" class=""gridBox"" runat=""server"">
</div>
<div id=""node2"" class=""gridBox"" runat=""server"">
</div>
<div id=""node3"" class=""gridBox"" runat=""server"">
</div>
<div id=""node4"" class=""gridBox"" runat=""server"">
</div>
<div id=""node5"" class=""gridBox"" runat=""server"">
</div>
<div id=""node6"" class=""gridBox"" runat=""server"">
</div>
<div id=""node7"" class=""gridBox"" runat=""server"">
</div>
<div id=""node8"" class=""gridBox"" runat=""server"">
</div>
<div id=""node9"" class=""gridBox"" runat=""server"">
</div>
</div>";
To your original question: have three strings with the possible "blocks" then assign the proper string:
string block1 = #"<div class=""mapContainer smallMap"">block 1</div>......";
string block2 = #"<div class=""mapContainer smallMap"">block 2</div>......";
string block3 = #"<div class=""mapContainer smallMap"">block 3</div>.......";
switch (myCond) {
case 1:
MapPlaceholder.InnerHtml= block1;
break;
case 2:
MapPlaceholder.InnerHtml= block2;
break;
case 3:
MapPlaceholder.InnerHtml= block3;
break;
}
Edit: looks like you need different approach. First, put all blocks inside the .aspx under MapPlaceholder control directly:
<div id="MapPlaceholder" runat="server">
<div class="mapContainer smallMap" id="smallGrid1" runat="server" visible="false">
block 1 contents here...
</div>
<div class="mapContainer smallMap" id="smallGrid2" runat="server" visible="false">
block 2 contents here...
</div>
<div class="mapContainer smallMap" id="smallGrid3" runat="server" visible="false">
block 3 contents here...
</div>
</div>
Having this, just show the proper control based on the condition:
switch (myCond) {
case 1:
smallGrid1.Visible = true;
break;
case 2:
smallGrid2.Visible = true;
break;
case 3:
smallGrid3.Visible = true;
break;
}
This way you don't have to mess with strings of raw HTML and can change the layout from the .aspx which is more convenient.
on Page Load you can insert what you need dynamically.
a tip: you can insert with a Label over its Text property an html block, javascript or jquery codes
Label myLabel = new Label();
myLabel.Text = #"html text";
Page.Controls.Add(myLabel);
If the question really is "how to place blocks of HTML onto the page" as a (very basic) example, you might find something like this useful:
ASPX code:
<div runat="server" id="mydiv"></div>
C# code:
mydiv.InnerHtml = "<span>hi</span>";
or
HtmlGenericControl c = new HtmlGenericControl("span");
c.InnerHtml = "hi";
mydiv.Controls.Add(c);
DataBinding is more for pushing dynamic values to page content from, e.g. a database.
The PlaceHolder control may be what you need:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.placeholder.aspx
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
protected void Button1_Click(object sender, EventArgs e)
{
Label NewLabel = new Label();
NewLabel.Text = "Hello World!";
PlaceHolder1.Controls.Add(NewLabel);
}
You can add HTML tags With concatenation of the string at label text or others
labelc.text="Html tags code here";