I have implemented image upload but can't find a way to display some animated gif image while uploading files. Here what I got so far:
<form method="post" action="/Images/Upload" enctype="multipart/form-data">
<input type="file" multiple name="ImageUploaded">
<input type="submit">
</form>
[HttpPost]
public ActionResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase hpf = Request.Files[i] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileNameThumb = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Content", "Images", "Thumb",
Path.GetFileName(hpf.FileName));
string savedFileName = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Content", "Images", "Full",
Path.GetFileName(hpf.FileName));
ImageModel.ResizeAndSave(savedFileNameThumb, hpf.FileName, hpf.InputStream, 80, true);
ImageModel.ResizeAndSave(savedFileName, hpf.FileName, hpf.InputStream, int.MaxValue, false);
}
return View();
}
I added now jquery form plugin and it works. Selected images are uploaded I show/hide preloader image.
I just still need to return view or uploaded image to display it after upload finish...
I return view from controller but nothing happens after upload.
$(function () {
$("#Form").ajaxForm({
iframe: true,
dataType: "html",
url: "/Images/Upload",
success: function (result) {
$('#loadingGif').remove();
},
beforeSubmit: function () {
$('<img id="loadingGif" src="../../Content/loader.gif" />').appendTo('body');
},
error: function (response) {
alert(response);
$('#loadingGif').remove();
}
});
});
you can use jQuery to post the form asynchronously and display an animated gif while you wait for the call to return.
$('form').submit(function () {
$(this).before('<img src="loader.gif" alt="Loading..." />');
// code to submit the form
return false;
});
EDIT:
When the view is returned in the success handler, if you e.g. return an <img> tag with the url of the uploaded image, you can use jQuery to display it:
$('body').append(result);
Related
halo guys can you help me to display image. How to display image in html from function javascript? ASP.NET
this is my html:
<div class="col-md-4">
<img id="DisplayImage" class="img-responsive thumbnail" width="200" height="200" />
</div>
javascript here =
var DisplayImage = function () {
var file = $("#SelectImage").get(0).files;
var data = new FormData;
data.append("ImageFile", file[0]);
$.ajax({
type: "GET",
url: '/Home/DisplayImage',
data: data,
contentType: false,
processData: false,
success: function (imgID) {
$("#DisplayImage").show();
$("#img_cgv").attr("src", "/UploadImage/" + imgID);
console.log(imgID);
}
})
}
my controller :
[HttpGet]
public ActionResult DisplayImage(int imgid)
{
Models.eCoalDataContext db = new eCoalDataContext();
var img = db.TBL_M_IMAGEs.SingleOrDefault(x => x.ID == imgid);
/*return File("image/jpg");*/
return File(img.IMAGE_TITLE, "image/jpg");
}
I don't have the code about your files, so in my demo I remove it. Below is a work demo to display image in html from function javascript, you can refer to it, hope it can help you.
Besides, in I have e.PNG in UploadImage folder like:
In Controller:
public class DisplayController : Controller
{
public IActionResult Index()
{
return View();
}
public ActionResult DisplayImage(int imgid)
{
imgid = 1;
var Images = new List<Images>()
{ new Images(){ID=1,IMAGE_TITLE="e.PNG"},
new Images(){ID=2,IMAGE_TITLE="flower.PNG"}
};
var img = Images.SingleOrDefault(x => x.Id == imgid);
return Json(img.IMAGE_TITLE);
}
}
Index view:
<input onclick="getA1Rates()" value="Click" type="button"/>
<div class="col-md-4">
<img id="img_cgv" class="img-responsive thumbnail" width="200" height="200" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
function getA1Rates() {
$.ajax({
type: "GET",
url: '/Display/DisplayImage',
contentType: false,
processData: false,
success: function (imgID) {
$("#img_cgv").attr("src", "/UploadImage/" + imgID);
console.log(imgID);
}
})
}
</script>
result:
I am using bellow code to insert the data to db. While Clicking the save button the data should be bind to the model and needs to be posted to controller action . But the data is not bind to the model. What is the issue in the bellow code . Any please help me to solve the below issue.
#(Html.Kendo().TextBoxFor(model => model.Code)
.HtmlAttributes(new { placeholder = "Enter Code", required = "required",
validationmessage="Code is Required" })
)
<input type="button" title="Save" id="btnsave" value="Save" onclick="submit()"/>
<script>
function submit(data) {
debugger;
console.log("Cosoledata "+JSON.stringify(data))
$.ajax({
type: "POST",
url: '#Url.Action("action", "controller")',
data: { data: #Model },
dataType: "json",
success: function (response) {
}
});
}
</script>
data: { data: #Model },
In the JavaScript script, you can directly get the Model data via the #Model.
To send the model data to the controller method, you could create a JavaScript object, then use JQuery to get the related property value (such as Code), then send the object to the controller method.
Please refer the following sample:
View page:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#btnCreate").click(function () {
var review = {}; //create a JavaScript Object.
//user JQuery to get the entered value, and set the property value.
review.ReviewID = $("#ReviewID").val();
review.MovieID = $("#MovieID").val();
review.goreRating = $("#goreRating").val();
review.shockRating = $("#shockRating").val();
review.jumpRating = $("#jumpRating").val();
review.plotRating = $("#plotRating").val();
review.supernaturalRating = $("#supernaturalRating").val();
review.starRating = $("#starRating").val();
//if you want to send multiple objects, you could create an array.
//var reviewlist = [];
//reviewlist.push(review);
$.ajax({
url: "/Home/AddReview",
method: "Post",
data: { "reviewViewModel": review } , // { "reviewViewModel": reviewlist },
success: function (response) {
alert(response);
},
error: function (response) {
console.log("error");
}
})
});
})
</script>
}
Controller method:
[HttpPost]
public IActionResult AddReview(ReviewViewModel reviewViewModel)
{
if (ModelState.IsValid)
{
//do something
}
return View();
}
The result as below:
I have a problem in downloading csv file using $.ajax(); code.
I have a controller which is returning the file as below.
public ActionResult ExportEx()
{
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
sb.Append("<tr>");
sb.Append("<td>1</td>");
sb.Append("<td>2</td>");
sb.Append("<td>3</td>");
sb.Append("<td>4</td>");
sb.Append("</tr>");
sb.Append("<table>");
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=student_" + DateTime.Now.Year.ToString() + ".xls");
this.Response.ContentType = "application/vnd.ms-excel";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
return File(buffer, "application/vnd.ms-excel");
}
I have index.cshtml file as below
<input type="submit" value="Export To Excel" title="Export To excel" />
<script type="text/javascript">
$(".tt").click(function () {
$.ajax({
url: '/Home/ExportEx',
type: 'POST',
data: {},
success: function (data) { },
complete: function (data) { }
});
});
</script>
If I call using <a class="tt" href="#Url.Action("ExportEx", new { })">export</a> I can download csv file. But through $.ajax call i can not download.
Kindly help me in this.
Thanks in advance.
$('button').click(function () {
window.location.href = '/Home/ExportEx';
});
Please help.
I am obviously no expert but using suggestions from this site, I think I am really close to doing the following
Be able to open a dynamically generated PDF in
a) a new Tab
b) an iframe
Hopefully, I just need a couple of lines of the correct syntax and I will be there.
I am dynamically generating the PDF in a controller using itextSharp
CONTROLLER
public FileStreamResult GetPdf()
{
...
return new FileStreamResult(Response.OutputStream, "application/pdf"){FileDownloadName = "download.pdf"};
}
VIEW
<input id="btnNewTab" type="button" value="New Tab" />
<input id="btnIframe" type="button" value="Iframe" />
<div id="pdfDiv"></div>
<script type="text/javascript">
$(function () {
$("#btnIframe").click(function () {
$.get('/PDFTest/GetPdf', function (pdf) {
alert(pdf.length); // Works as expected
// What do I need to put here to get the pdf to appear in a iframe
});
});
$("#btnNewTab").click(function () {
// asks me if I want to Open or Save the PDF.
// If I choose Open, the PDF opens in a completely new Window.
// Instead of the dialog, I just want the PDF to open in a new Tab
// I am probably going about this in completely the wrong way.
var HTML = "<iframe src='/PDFTest/GetPdf' style='width: 100%; height: 600px' ></iframe>";
$('#pdfDiv').html(HTML);
});
});
</script>
In response to your suggestion Darin, I changed the Controller to:
public FileStreamResult GetPdf(someInfo from View)
{
...
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline;test.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}
Having done that, your suggestions worked fine but I realise that I did not explain my intentions clearly enough. I have therefore changed the VIEW to reflect what i am trying to do.
input id="btnNewTab" type="button" value="New Tab" />
<input id="btnIframe" type="button" value="Iframe" />
<iframe id="iframe"></iframe>
<div id="pdfDiv">
</div>
<script type="text/javascript">
$(function () {
$("#btnIframe").click(function () {
$.ajax({
url: '/PDFTest/GetPdf',
type: "GET",
data: json, // This line will not be a problem
dataType: "json",
contentType: "application/pdf", // This line might be a problem
success: function (pdf) {
// What to I need to need to do to display the PDF in the above iframe
$("#iframe").attr("src", pdf); // HTTP Error 400 - Bad Request.
}
});
});
$("#btnNewTab").click(function () {
$.ajax({
url: '/PDFTest/GetPdf',
type: "GET",
data: json, // This line will not be a problem
dataType: "json",
contentType: "application/pdf", // This line might be a problem
success: function (pdf) {
// What to I need to need to do to disply the PDF in a new window
}
});
});
});
</script>
Action:
public ActionResult GetPdf()
{
byte[] pdf = ...
Response.AppendHeader("Content-Disposition", "inline;test.pdf");
return File(pdf, "application/pdf");
}
To open in new Tab/Window:
#Html.ActionLink("view pdf", "getpdf", "somecontroller", null, new { target = "_blank" })
To open in an iframe your code looks fine. Just make sure to set the Content-Disposition header to inline.
I try something.I apologize in advance for my english.
My Action code;
public PartialViewResult showProduct()
{
var query = db.Categories.Where((c) => c.CategoryID == 4);
return PartialView("_EditCategory",query);
}
My view code:
#using (Ajax.BeginForm(
"showProduct",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "result"
}))
{
<input type="submit" value="Get" />
}
<div id="result">
</div>
When i pushed the submit button ( which value is get) the results return but in another page like http://localhost:57616/Home/showProduct but i want return to result div in index page.
Any one can help me?
So, how I handled this myself was something like this:
$(document).ready(function () {
var options = {
target: "#mytargetdiv",
url: '#Url.Action("Edit", "IceCream")',
};
$("#editIceCreamForm").submit(function () {
$(this).ajaxSubmit(options);
return false;
}
// other stuff
});
in other places, where I wanted to do in-place editing of things I'd do something like this:
<input type="button" id="someid" value="Edit" data-someid="#Model.SomeId"/>
and then some ajax like so:
$(function () {
$("#someid".click(function () {
var theId = $(this).data('someid');
$.ajax({
type: "GET",
data: "id=" + theId,
url: '#Url.Action("Edit", "Something")',
dataType: "html",
success: function (result) {
$('#targetdiv').html(result);
}
});
});
});
So, if you're not interested in using jQuery and want to use the MS Ajax stuff, are you including the MicrosoftAjax.js and MicrosoftMvcAjax.js files on the page? If you don't have those, I believe what will happen is it just does the default (non-Ajax) submit.