Open a PDF file in AJAX POST - javascript

I am doing ajax POST as:
$.ajax({
type: 'POST',
url: rootUrl("Home/PrintInvoice/12"),
success: function (result) {
$("#TestInvoicePrint").empty();
$("#TestInvoicePrint").html(result);
window.open(result);
}
});
Where I am getting PDF file in result from MVC action as,
public ActionResult PrintInvoice(long ID)
{
var data = db.Documents.Where(x => x.InvoiceNumber == ID);
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("~/Reports/InvoiceDocument.rpt"));
ConnectionInfo ConnInfo = new ConnectionInfo { ServerName = "10.0.0.154,1433\\sqlexpress", UserID = "CueReader", Password = "CueReader#123", DatabaseName = "Cue" };
ParameterFieldDefinitions parmFields = rd.DataDefinition.ParameterFields;
ParameterValues pvals = new ParameterValues();
rd.ParameterFields["DocumentID"].CurrentValues.IsNoValue = true;
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(stream, "application/pdf");
}
How can I use the PDF file into my DOM Element from ajax POST?

it would be better if you could have the ajax give you a url (dynamic?) and then update an object data= attribute

Related

How to fix Ajax call "The parameters dictionary contains a null entry........."

I'm trying to send my data via ajax call to the controller but I check all my code I debug it all values are filled but it continuously shows me this error. event its also show me ON MVC call As Well
The parameters dictionary contains a null entry for parameter 'BrandId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Forms(System.Collections.Generic.IEnumerable1[System.Web.HttpPostedFileBase], System.String, Int32, Int32, Boolean, Int32)'in'AdminDevVersion.Controllers.HomeController'`. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
i have already debugged the code and I have checked if all the values are filled.
My Ajax Code
function uploadSubmitHandler() {
var PName = $("#ProductName").val();
var Category = $("#CategoryDropDown").val();
var Brand = $("#BrandDropDown").val();
var SubCategory = $("#SubCategory").val();
var ProductDescription = $('textarea.textarea-editor').val();
var NewOROldRadio = $("input[name='ProductStatus']:checked").val();
if (state.fileBatch.length !== 0) {
var data = new FormData();
for (var i = 0; i < state.fileBatch.length; i++) {
data.append('files', state.fileBatch[i].file, state.fileBatch[i].fileName);
}
data.append('ProductName', PName);
data.append('CategoryId', Category);
data.append('BrandId', Brand);
data.append('IsNewStatus', NewOROldRadio);
data.append('SubCategoryId', SubCategory);
data.append('Description', ProductDescription);
$.ajax({
type: 'POST',
url: options.ajaxUrl,
data: data,
cache: false,
contentType: false,
processData: false
});
}
}
Controller Code
[HttpPost]
public ActionResult Forms(IEnumerable<HttpPostedFileBase> files, String ProductName, int CategoryId, int BrandId, bool IsNewStatus, int SubCategoryId)
{
List<string> FileNames = new List<string>();
string ImageName = null;
TblProduct InsertProduct = new TblProduct();
if (ModelState.IsValid == true)
{
InsertProduct.Name = ProductName;
InsertProduct.IsActive = IsNewStatus;
InsertProduct.BrdId = BrandId;
InsertProduct.CatId = SubCategoryId;
InsertProduct.Image = ImageName;
InsertProduct.Created = DateTime.Now;
InsertProduct.IsActive = true;
_RepoProduct.Insert(InsertProduct);
_RepoProduct.Save();
TblProRelImg RelatedImages = new TblProRelImg();
foreach (HttpPostedFileBase file in files)
{
string _path = System.IO.Path.Combine(Server.MapPath("~/Content/Images/"), file.FileName);
file.SaveAs(_path);
if (file == files.First())
{
ImageName = file.FileName.ToString();
}
else
{
RelatedImages.PrdID = InsertProduct.ID;
RelatedImages.Image = file.FileName;
_ReporRelatedImages.Insert(RelatedImages);
_ReporRelatedImages.Save();
}
FileNames.Add(file.FileName);
}
ViewBag.CategoryId = Logics.Category();
ViewBag.BrandInfo = new SelectList(DbContext.TblBrands, "Id", "Name");
}
return View();
}
I have expected to send data to the controller
parse your BrandId to int like blow and append to your data
parseInt(Brand)

Download a file through ajax request in asp.net MVC

I am trying to download file through ajax call in asp.net
my javascript:
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var data = query.filter(filters).data;
var strAccountCodes = '';
for (var i = 0; i < data.length; i++) {
strAccountCodes += data[i].AccountCode + ",";
}
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes }
});
my action method:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
return File(output, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
code is executing without any errors but it's not downloading any file.
is that anything i am missing?
You should know that AJAX call is not intended to download CSV file directly. Therefore, you can create a byte array from MemoryStream instance and store it inside Session or TempData variable, then return 'successful' state to enable redirect on AJAX success response:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
// creates byte array from stream
TempData["Output"] = output.ToArray();
// returns successful state
return Json("Success", JsonRequestBehavior.AllowGet);
}
Second, create a controller action with GET method and pass stored byte array from Session or TempData into FileResult:
public ActionResult DownloadCSV()
{
// retrieve byte array here
var array = TempData["Output"] as byte[];
if (array != null)
{
return File(array, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
else
{
return new EmptyResult();
}
}
Finally, handle success response to include location.href which will redirect to controller returning FileResult to download CSV file:
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadCSV", "ControllerName")';
}
}
});
As an option, you could pass CSV file name as parameter from AJAX response using query string.
Related issue:
Creating a byte array from a stream

Ajax call to ASP.NET MVC Controller Returns 404 when Json Length is too Long

I have a simple ajax call which is passing a json string to a controller action and if the content portion of the json is too long, or the json string in general, the server returns a 404, if I shorten the content, it the request resolves and completes correctly.
I thought it was do to the 8k limit of Microsoft's JavaScriptSeralizer, but I have updated the MaxJsonLength, with no luck. Can somebody please tell me what's going on here?
Here is my ajax request (Note: This is using Knockout.js)
self.updatePost = function () {
var postToUpdate = ko.toJS(self.selectedPost);
postToUpdate.Content = $("#wmd-input").val();
console.log(postToUpdate);
$.getJSON('/blogs/posts/update', {post: ko.toJSON(postToUpdate)}, function(post) {
if (post) {
// remove the selected post and add the updated post
self.posts.remove(self.selectedPost());
var updatedPost = new Post(post);
self.posts.unshift(updatedPost);
self.selectedPost(updatedPost);
$("#ghost-list li:first").trigger('click');
// show alert
}
});
};
The C# Controller Action
public JsonResult Update(string post)
{
var seralizer = new JavaScriptSerializer();
seralizer.MaxJsonLength = int.MaxValue;
seralizer.RecursionLimit = 100;
var selectedPost = seralizer.Deserialize<Post>(post);
var student = students.GetStudentByEmail(User.Identity.Name);
var blog = db.Blogs.SingleOrDefault(b => b.StudentID == student.StudentID);
var postToUpdate = blog.BlogPosts.SingleOrDefault(p => p.ID == selectedPost.ID);
if (postToUpdate != null)
{
// update the post fields
postToUpdate.Title = selectedPost.Title;
postToUpdate.Slug = BlogHelper.Slugify(selectedPost.Title);
postToUpdate.Content = selectedPost.Content;
postToUpdate.Category = selectedPost.Category;
postToUpdate.Tags = selectedPost.Tags;
postToUpdate.LastUpdated = DateTime.Now;
if (selectedPost.Published)
{
postToUpdate.DatePublished = DateTime.Now;
}
// save changes
db.SaveChanges();
var jsonResult = Json(seralizer.Serialize(selectedPost), JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
return Json(false, JsonRequestBehavior.AllowGet);
}
Have you tried using the post method:
$.post('/blogs/posts/update', {post: ko.toJSON(postToUpdate)}, function(post) {
if (post) {
// remove the selected post and add the updated post
self.posts.remove(self.selectedPost());
var updatedPost = new Post(post);
self.posts.unshift(updatedPost);
self.selectedPost(updatedPost);
$("#ghost-list li:first").trigger('click');
// show alert
}
}, 'json');
Try this at web config
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="500000000"/>
</webServices>
</scripting></system.web.extensions>

Catching ajax file in ASP.Net MVC Controller

I want to upload file using ajax to an ASP.Net MVC Controller
My JavaScript code looks like this, basically every time the user changed the input value, it will automatically upload the file to the controller
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
$('input[name=default_export_filename]').change(function() {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (file.type.match(/spreadsheet/) || file.type.match(/ms-excel/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("default_export_filename", file);
}
}
}
if (formdata) {
$.ajax({
url: root + mod + '/uploaddef',
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
}
});
}
});
In the controller side, I couldn't catch that file using this
[HttpPost]
public ActionResult UploadDEF(HttpPostedFileBase file)
{
var jsonData = new
{
response = 3
};
return Json(jsonData); ;
}
Or this
[HttpPost]
public ActionResult UploadDEF(FormCollectionfile)
{
var jsonData = new
{
response = 3
};
return Json(jsonData); ;
}
The file argument is always null. But in the firebug, I can see that the browser is posting the file to the server. With what object should I catch the file?
I realize the FormData object is not supported in older browser, but my clients are all using the latest browser. So that is not a problem.
The problem is solved.
It turns out I don't have to give any parameters to the controller's method. The files are available through Request object.
Thanks all
You can't use ajax POST to upload a file like this, must be a form submit.
Have a look at component like AjaxUploadify or similar.

MVC 3 .NET Fill fields dynamically

I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}

Categories

Resources