.NET "Request.Files" capture extra input - c#

I made a dynamically multi upload form with file type inputs. When you select a file new file input will appear. When submit the form all inputs captured by "Request.Files" at code behind.
There is no problem when i generate those file in a .aspx file but when i use Web User Control (.ascx) page "Request.Files" add 1 more request (for the blank file input).
Why ascx count the balnk input?
I share the codes below:
MultiImage.ascx
<ul id="imagesToUpload">
<li><input type="file" class="imageToUpload" runat="server" /></li>
</ul>
<script type="text/javascript">
$('.imageToUpload').live('change', function () {
$(this).parent().append('<div class="imageInfoContainer"><span>Yüklenen görsel: ' + $(this).val() + ' </span><div class="deleteImage">Sil<div><div>');
if ($('input:file').length < <%= MaxImageNumber %>) {
$(this).parent().parent().append('<li><input type="file" class="imageToUpload" runat="server" /></li>');
}
});
$('.deleteImage').live('click', function () {
$(this).parent().parent().remove();
if ($('input:file').length < 1) {
$('#imagesToUpload').html('<li><input type="file" class="imageToUpload" runat="server" /></li>');
}
});
</script>
MultiImage.ascx.cs
var imageCollection = Request.Files; //Counts all file inputs included the blank one

Why ascx count the balnk input?
You mean why does HttpRequest object count that input? Because it is present in the request. You can however easily check if it is empty or not by looking at the HttpPostedFile.ContentLength property of each element inside Files collection.

Related

Print out values from text file to text area

so my first attempt at asking the question was idiotic - I do apologise
So I am reading the contents of a text file - which is just rows of numbers. I am trying to calculate the sum of each row and print the answer out individually in descending order.
Here is the code in my controller :
public void ReadFromText()
{
Array LogFileData = null;
var logFileNameWithPath = Server.MapPath(#"~/Docs/Q1InputFile.txt");
if (System.IO.File.Exists(logFileNameWithPath))
{
LogFileData = System.IO.File.ReadAllLines(logFileNameWithPath);
foreach (var line in LogFileData)
{
//code goes here
}
}
ViewBag.logFileContent = LogFileData;
}
I am struggling to send the content from the text file to the text area and with the for each in order to calculate the sum of each row.
Here is the code for the view :
<h2>Question1</h2>
<div class="jumbotron">
<p class="lead">Please click the button to load the results</p>
<input type="button" title="LoadAnswer" value="Click me" id ="btn_run")
onclick="location.href='#Url.Action("ReadFromText", "Question1")'" />
#if (ViewBag.logFileContent != null)
{
foreach (string dataLine in ViewBag.logFileContent)
{
#dataLine
<br />
}
}
</div>
#Html.TextArea("ReadFromText", "Question1")
<div>
#Html.ActionLink("Back to Home", "Index", "Home")
</div>
Sorry this a basic question - but I new and trying to learn from this
Please advise
Assuming that your button is html and in browser on client side and file is residing on server in your solution directory (not on client side)
I would do following
When a button in browser is pressed I will fire an ajax call to server.
On server controller would open a file stream to this file and read lines one by one or whatever way you want to do with them and get the output sent out in json format.
When server returns output to ajax response i will replace the text area with that response or append it if needed.
All these three steps can be done individually with test data. I would first create an ajax test and on controller return a number and work on js to populate it in text field. Once that is done you only need to work on file read function in controller and return what is in file or summed from file etc.
On click of button make an AJAX call
Sample Ajax code:
$.ajax({
type : 'POST',
url : '#Url.Action("your controller and actions goes here")',
dataType : 'json',
data : {
//Send file path if it is dynamic
},
success : function (data) {
//Logic to format and display your text file data
},
error : function (ex) {}
});
C# - Server side code:
string text;
var fileStream = new FileStream(#"c:\file.txt",FileMode.Open,FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
send text in the JSON format to the client and display it as per your requirment
Refer this link for AJAX implementation http://dotnetmentors.com/mvc/jquery-ajax-call-with-jsonresult-in-asp-net-mvc.aspx
I prefer to read line by line from txt file and then I create a stringBuilder and send it to a textare element like this.
List<string> linesFromFile= File.ReadAllLines(filePath).ToList();
StringBuilder str = new StringBuilder();
foreach (string item in linesFromFile)
{
str.AppendLine(item);
}
ViewBag.RobotsTxt = str;

upload multiple image to sqlserver using json mvc asp.net

I am needing to insert a set of information in the database sqlserver data, but along with them some pictures along with some string. I am wanting to move everything by Json.
below is the input to select the image
<th>
<div class="form-group">
<label for="legendaFoto5">Legenda</label>
<input type="text" class="form-control" id="legendaFoto5" placeholder="Legenda da Foto">
</div>
</th>
and below this the part where I pass along to Json, not this going well until I changed the first "sfoto1InputFile" to be able to upload, but it did not work.
<script type="text/javascript">
$(document).ready(function () {
$("#salvarLevantamentoFicha").click(function (evt) {
var sfoto1InputFile = $("#foto1InputFile").get(0).files[0];
var sfoto2InputFile = $("#foto2InputFile").image;
var sfoto3InputFile = $("#foto3InputFile").image;
var sfoto4InputFile = $("#foto4InputFile").image;
var sfoto5InputFile = $("#foto5InputFile").image;
var strlegendaFoto1 = $("#legendaFoto1").val();
var strlegendaFoto2 = $("#legendaFoto2").val();
var strlegendaFoto3 = $("#legendaFoto3").val();
var strlegendaFoto4 = $("#legendaFoto4").val();
var strlegendaFoto5 = $("#legendaFoto5").val();
$.getJSON("#Url.Content("~/CadLevantamentoAmbiental/SalvarFichaLevantamentoTC")", {
_sfoto1InputFile: sfoto1InputFile,
_sfoto2InputFile: sfoto2InputFile,
_sfoto3InputFile: sfoto3InputFile,
_sfoto4InputFile: sfoto4InputFile,
_sfoto5InputFile: sfoto5InputFile,
_strlegendaFoto1: strlegendaFoto1,
_strlegendaFoto2: strlegendaFoto2,
_strlegendaFoto3: strlegendaFoto3,
_strlegendaFoto4: strlegendaFoto4,
_strlegendaFoto5: strlegendaFoto5
});
});
});
</script>
There are several things that ypu must take into account, and several differences between browsers. So the best that you can do is to use and existing jQuery plugin to get this done, for example:
jQuery File Upload Demo
malsup jQuery Form plugin
The second one is a more general solution, to post a whole form including the file uploads that it contains.
If you try to do it by yourself, without using a plugin, you'll get into big trouble.

How I can generate the pdf using AddImageUrl from ABCpdf after the page is loaded complete

I want to add the thumbnail of a web page to pdf document,
I added like this:
Doc generatedoc = new Doc();
generatedoc.HtmlOptions.UseScript = true;
string urlToHtmlPage = "http://example.com?param1=30&param2=true";
int generatedId = generatedoc.AddImageUrl(urlToHtmlPage);
generatedoc.Save(HttpContext.Current.Server.MapPath("htmlimport.pdf"));
generatedoc.Clear();
In url I send two parameters, depending on a parameter in page is added a class for various html tags, for example:
<div class="cssClass <%=param2==true?"secondCssClass":""%>">some html tags</div>
or
<span class="<%= param2==true?"secondCssClass":"" %>"> some text </span>
Inside the style
<style type="text/css">
.secondCssClass
{
display: none;
}
</style>
pdf is generated ok but secondCssClass is not added to my tags and css is not applying
I try to set big time out but also css is not applying
I set time out like this:
generatedoc.HtmlOptions.Timeout = 1000000;
or
generatedoc.HtmlOptions.OnLoadScript = "(function(){ window.ABCpdf_go = false;
setTimeout(function(){ window.ABCpdf_go = true; }, 1000000); })();";
or RenderWait() and RenderComplete()
generatedoc.HtmlOptions.OnLoadScript = #"
window.external.ABCpdf_RenderWait();
window.external.ABCpdf_RenderComplete(true);";
but anyway CSS did not apply
when I load url in browser css is applying
some proposals?
Based on your response to the comment that you see the issue even in the browser tells that this is not an ABCPDF issue.
I think the problem lies in the following:
<div class="cssClass <%=param2==true?"secondCssClass":""%>">some html tags</div>
AND
<span class="<%= param2==true?"secondCssClass":"" %>"> some text </span>
If that code is exactly what you have in your running code, then you will need to make an adjustment those lines:
Accessing URL parameters, you need to use the Request object
URL parameters are text, and your comparison has them as boolean
Code should be as follows:
<div class="cssClass <%= Request.QueryString("param2")=="true"?"secondCssClass":"" %>">some html tags</div>
AND
<span class="<%= Request.QueryString("param2")=="true"?"secondCssClass":"" %>"> some text </span>
I recommend that you test this in the browser prior to testing it via ABCPDF.

Link Dynamic URL to div in Umbraco

I am building a site using Umbraco and I have a div that currently has a link inside it. The current code is:
<div class="callout col-sm-4 leftCtaLink">
<p>#CurrentPage.leftDescription</p>
<a class="primary-bg" href="#CurrentPage.leftCtaLink"><img class="svg-inject" src="#Umbraco.Media(CurrentPage.leftIcon).umbracoFile" alt="Icon" />#CurrentPage.leftCtaText</a>
</div>
This works and only the bottom half of the callout links to the correct page. The client wants the whole div to be linkable now though, so I thought I'd do this with jQuery. Here is that:
<script type="text/javascript">
$(document).ready(function () {
$(".leftCtaLink").click( function() {
window.location=$(this).find("a").attr("#CurrentPage.leftCtaLink");
return false;
});
});
</script>
The issue is, that when the div is clicked on, it takes me to the website's url with /undefined at the end of it. Can anyone tell me what I need to change in the JS to have it use the correct URL that was input in the CMS?
Change to attr("href").
$(document).ready(function () {
$(".leftCtaLink").click( function() {
window.location=$(this).find("a").attr("href");
return false;
});
});

Reloading Partial View with JQuery

I have a page with a video at the top and a list of videos you can choose from. Currently, clicking a link in the video list will reload the entire page. I need it to only refresh the partial view I have containing the video at the top of the page.
I saw several posts here on SO showing how to reload partial views with JQuery, but couldn't get it to work correctly in my situation. I'm unsure how to pass the correct id of the video along.
Controller:
public ActionResult Videos(int topVideo = 0)
{
VideosModel model = new VideosModel();
model.Videos = StatsVideoService.GetEntityList(new Lookup(TableStatsVideo.IsDeleted, false)).OrderByDescending(x => x.DateCreated).ToList();
if (topVideo == 0)
model.TopVideo = model.Videos.First();
else
{
model.TopVideo = model.Videos.Where(x => x.StatsVideoId == topVideo).FirstOrDefault();
if (model.TopVideo == null)
model.TopVideo = model.Videos.First();
}
return View(model);
}
View:
#model Project.Models.VideosModel
<section class="videos">
<div id="top_video">
#{Html.RenderPartial("StatsVideo", Model.TopVideo);}
</div>
<ul>
#foreach (var item in Model.Videos)
{
<li>
<div class="videoList">
<a href ="#Url.Action("Videos", "Home", new { topVideo = item.StatsVideoId })">
<img src="#Url.Content("~/Content/img/video-ph.png")" />
</a>
<p class="videoTitle">#item.Title</p>
</div>
</li>
}
</ul>
</section>
If there's any more information needed, please let me know.
After several hours of bashing my head against the wall, I got it to work! Just as a reference to anyone else in the future who's viewing this article, here's how I got it to work:
I set the onclick of the link to point to a javascript method, passing in the id of the video as a parameter:
#foreach (var item in Model.Videos)
{
<li>
<div class="videoList">
<a href ="#" onclick="updateTopVideo(#item.StatsVideoId)">
<img src="#Url.Content("~/Content/img/video-ph.png")" />
</a>
<p class="videoTitle">#item.Title</p>
</div>
</li>
}
And then I included this script in the view at the bottom:
<script>
var updateTopVideo = function (itemId) {
var url = '#Url.Content("~/Home/StatsVideo/")';
url = url + itemId;
$.get(url, "", callBack, "html");
};
var callBack = function (response) {
$('#top_video').html(response);
};
</script>
Finally, I added a method to my controller that would return the partial view needed for the video at the top of the screen:
public ActionResult StatsVideo(int Id)
{
IStatsVideo vid = StatsVideoService.GetEntity(new Lookup(TableStatsVideo.StatsVideoId, Id));
if (vid == null)
vid = StatsVideoService.GetEntityList(new Lookup(TableStatsVideo.IsDeleted, false)).OrderByDescending(x => x.DateCreated).FirstOrDefault();
return PartialView(vid);
}
This code should be fairly easy to understand. Basically, the onclick calls the first javascript method, which then calls the controller. The controller builds the partial view and returns it. The first javascript method passes it to the second javascript method which sets the html of the div "top_video" to be the returned partial view.
If anything doesn't make sense, or anyone's having trouble with this in the future, let me know and I'll do my best to offer some help.
I think there may be several confusing and inconsistent elements here.
First, you are returning a full view instead of a partial view. This reloads all containing elements, not just the part that is relevant to your partial view.
Second, you are using Url.Action, which only generates the url. I would recommend using Ajax.ActionLink, which allows you to do fully ajax calls, refreshing the content of your partial div and updating a target div element.
instead of:
<div class="videoList">
<a href ="#Url.Action("Videos", "Home", new { topVideo = item.StatsVideoId })">
<img src="#Url.Content("~/Content/img/video-ph.png")" />
</a>
<p class="videoTitle">#item.Title</p>
</div>
try the more modern solution
<div class="videoList">
#Ajax.ActionLink(
"Videos",
"Home",
"new { topVideo = item.StatsVideoId },
new AjaxOptions {
HttpMethod = "GET",
OnSuccess = "handleSuccess"
}
)
</div>
This way you can be very specific on what you want each link to do, and you can pass along multiple parameters as well as define a callback function. You can also use "UpdateTargetId" in your ajax options to load your newly refreshed partial view into a DOM element.
You can remove the around the image and just store the url generated by the Url.Action in a data-href attribute.
Then you can use the jquery load method to load the data:
$(".videolist>img").click(function () {
$("#content").load($(this).data("href"));
});
I created a fiddle that loads content dynamically here, so you can play with it if you want: http://jsfiddle.net/bTsLV/1/

Categories

Resources