Export CSV using jQuery AJAX call - javascript

I have some code to export the results of a search to a CSV file:
$("#exportButton").click(function () {
var url = "/Stuff/ExportSearchResults";
var searchInput = readInput();
$.post(url, searchInput, function (data) {
// This is where I'm clueless.
// I'm getting data back but not sure how to make the
// browser show a prompt to download the file.
console.log(data);
});
});
At the server side (ASP.NET MVC 4) there's this:
[HttpPost]
public FileResult ExportSearchResults(SearchInput model)
{
string csv = GenerateCsv(model);
return File(new UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}
So the good thing is that I'm getting data back in the console. I'm just not sure how I would make the browser show a prompt to download a file.

Here for this question we can go with comment from https://stackoverflow.com/users/5349021/sreepathy-sp
At Client side
$("#exportButton").click(function () {
var url = "/Stuff/ExportSearchResults";
var searchInput = readInput();
window.location.href = '/Stuff/ExportSearchResults?searchInput='+searchInput ;
});
At server side
[HttpGet]
public FileResult ExportSearchResults(string model)
{
string csv = GenerateCsv(model);
Stream stream = new MemoryStream(new UTF8Encoding().GetBytes(csv));
return File(stream , "text/csv", "Export.csv");
}
Hope this will help you out.

Related

How could I pull data from several db tables to automate data entry for user in ASP.NET MVC 5 application?

I have a form in my ASP.NET MVC 5 application that is made up of several different entities that are stored in my database. I am trying to set it up so that, when a user types in the name of a particular entity (let's say a Shipper), the fields in the form that pertain to that entity (e.g. the fields in the Shipper section) are automatically populated with that Shipper's data. Here is what I have tried:
I wrote a class to connect to the database that returns a dataset of Shipper data.
public class DbConnection
{
private string _connectionString = "the connection string";
public DbConnection()
{
}
public DataSet GetShipperData()
{
DataSet shipperData = new DataSet();
try
{
//TODO: replace command with stored procedure name
using(SqlConnection dbConn = new SqlConnection(_connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter("select * from dbo.shipper", dbConn))
{
sda.Fill(shipperData);
}
}
return shipperData;
}
catch
{
return null;
}
}
}
}
Here is the method I've written to get the shipper dataset in the controller for the form:
public string[] GetShipperData()
{
DbConnection conn = new DbConnection();
var shipperData = conn.GetShipperData();
List<Shipper> listOfShipperData = shipperData.Tables[0].AsEnumerable().Select(datarow => new Shipper { Name = datarow.Field<string>("Name") }).ToList();
return listOfShipperData;
}
Finally, here is the javascript code in the view where the form is located. I'm using jQuery to call the GetShipperData method in the controller. I have omitted the markup for brevity:
$("#theShipperField").blur(function () {
$.get('#Url.Action("GetShipperData")', function (data) {
var shipperFields = document.getElementsByClassName('form-control shipper');
$(shipperFields).attr("value", data);
});
});
The first error I'm getting is this: In the Shipper fields, I am getting this instead of the data I want: System.Collections.Generic.List1[appname.Models.Shipper]. I think it's because javascript obviously can't work with shipper data, so I need this to be in the form of strings. I'm unsure of how to do this. I would be open to doing this a completely different way, so any help is greatly appreciated. Please let me know if I can provide any additional information.
First: try use Entity Framework
Having your db model in Entity framework I should create web api
[System.Web.Http.Route("api/GetShippers")]
[System.Web.Http.HttpGet]
public IEnumerable<Shipper> GetShippers()
{
var shippers= unitOfWork.GetShippers();
return shippers;
}
After that in your js code
dataservice.js
var dataService = new function () {
getShippers = function (callback) {
$.getJSON(window.applicationBaseUrl + 'api/GetShippers', function (data)
{
callback(data);
});
};
}
index.cshtml
#section scripts{
<script type="text/javascript">
$(document)
.ready(function() {
dataService.getShippers(DoSomething);}
function DoSomething(shippersData) {console.log(shippersData);}
</script>
}

Not Showing the output of Json Data from controller to the view

I am trying to to show the Json data from controller to the view. It works fine in my test project, but when I copied the work in the main project it gives error.
It says Url does not exist in the current context. Although it works fine in the test project and doesn't give this error.
Controller Code -
public JsonResult GetFreight()
{
string url = "https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate.json?length=22&to_postcode=3000&from_postcode=2000&weight=1.5&height=7.7&width=16&service_code=AUS_PARCEL_REGULAR";
//synchronous client.
var client = new WebClient();
client.Headers.Add("auth-key:a1234567-abcd-abcd-1234-1234567890abc");
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return Json(jsonContent, JsonRequestBehavior.AllowGet);
}
View Code
<script>
var weather = Object();
$(document).ready(function () {
$.get("#Url.Action("GetFreight", "ShoppingCart")", function (response) {
//response
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
});
});
</script>
<td>Freight = <span data-bind="text:postage_result.total_cost"></span></td>
I want to mention one more thing- In the main project the view is placed in another subfolder called "ShoppingCart" so do I need to change anything in the script when calling the method from the controller? Any help will be appreciated.
Thanks.

Ajax call don't receive html content from MVC Action

This is my action:
[HttpGet]
public virtual ActionResult DesignItemsList(int dealId, string sort)
{
return View(MVC.Designer.Views._DesignItems, _designerService.GetDesignItems(dealId, sort));
}
The GetDesignItems() method is working correctly.
$(document).ready(function() {
$('.product__filtr__form__select').change(function(e) {
var sort = $(this).val();
var urlFilter = $('#url-filterPanel-hidden-field').val();
var dealId = $('#dealId-hidden-field').val();
var urlItems = $('#url-items-hidden-field').val();
$.ajax({
type: "GET",
data: {
dealId: dealId,
sort: sort
},
url: urlItems,
success: function (result) {
console.log(result);
$('#Product-Items-Container').html(result);
}
});
});
});
Request is working too, but I don't receive the response and get only 500 code.
500 error code means, Internal server error. Your action method failed to process thie request you sent.
Since it is a GET action method, You may add the query string parameters to the url.
var sort = $(this).val();
var dealId = $('#dealId-hidden-field').val();
var urlItems = $('#url-items-hidden-field').val();
urlItems = urlItems+"?dealId="+dealId+"&sort"+sort;
//Let's write to console to verify the url is correct.
console.log(urlItems);
$.get(urlItems,function(res){
console.log('result from server',res);
$('#Product-Items-Container').html(res);
});
Try to replace the view name inside your controller:
return View("YourControllerView", _designerService.GetDesignItems(dealId, sort));
Because I was tested your ajax request and find out that it works fine.
And pay attention to view location. This view must be located inside the directory with the same name as your controller or inside the shared dictory

How to populate javascript variable with JSON from ViewBag?

I have this Index action:
public ActionResult Index()
{
var repo = (YammerClient) TempData["Repo"];
var msgCol = repo.GetMessages();
ViewBag.User = repo.GetUserInfo();
return View(msgCol.messages);
}
GetMessages returns a list of POCO messages and GetUserInfo returns a POCO with the info of the user (id, name, etc).
I want to fill a javascript variable with the JSON representation of the user info.
So I would want to do something like this in the view:
...
<script>
var userInfo = "#ViewBag.User.ToJson()"
</script>
...
I know that doesn't work, but is there a way to do that? I want to avoid having to do an ajax request once the page is loaded just to get the user info.
In View you can do something like this
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var userInfoJson = jss.Serialize(ViewBag.User);
}
in javascript you can use it as
<script>
//use Json.parse to convert string to Json
var userInfo = JSON.parse('#Html.Raw(userInfoJson)');
</script>
Was using this solution for simple objects. But I had some problems getting an array to js objects so I'll just leave what I did here.
C#
#{
using Newtonsoft.Json;
ViewBag.AvailableToday = JsonConvert.SerializeObject(list);
}
js
var availableToday = JSON.parse('#Html.Raw(ViewBag.AvailableToday)');
Client-Side Code:
This is an ajax call to a .Net MVC Controller:
var clientStuff;
$.ajax({
type: 'GET',
url: '#Url.Action("GetStuff", "ControllerName")',
data: {},
dataType: "json",
cache: false,
async: false,
success: function (data) {
clientStuff = data;
},
error: function(errorMsg) {
alert(errorMsg);
}
});
Server-Side Code:
CONTROLLER:
public JsonResult GetStuff()
{
return Json(_manager.GetStuff(), JsonRequestBehavior.AllowGet);
}
MANAGER:
public IEnumerable<StuffViewModel> GetStuff()
{
return _unitofWork.GetStuff();
}
UNIT OF WORK:
public IEnumerable<StuffViewModel> GetStuff()
{
var ds = context.Database.SqlQuery<StuffViewModel>("[dbo].[GetStuff]");
return ds;
}
Unit of Work can be a query to a sproc (as I have done), a repository context, linq, etc.
I'm just calling a sproc here for simplicity, although it could be argued that the simplicity lies with Entity Framework and Linq.
You can change this line :
ViewBag.User = repo.GetUserInfo();
To
ViewBag.User = new HtmlString(repo.GetUserInfo());
You should add using Microsoft.AspNetCore.Html; or using System.Web; if HtmlString is not accessible.

Updating view by calling Action Method from Javascript

I have a javacript Like this:
<script>
function GetFromDate() {
var dt1 = document.getElementById('fromDate').value;
var dt2 = document.getElementById('toDate').value;
var url = "Statistics/Excel/" + dt1 + "!" + dt2;
window.location.href = url;
return false;
};
</script>
and in controller my ActionResult is like this:
public ActionResult Excel(string id)
{
\\ View Creation
if(SomeLogic)
{
\\Excel Download Options
}
return View(viewModel);
}
Though it is perfectly working with the Excel Downloading option but it is not returning the View. Any Suggestions?
For more information "viewModel" object contains the perfect data to be displayed.
If your response is returning a file download, then this counts as your Http response, you aren't able to then do a redirect in the same action.

Categories

Resources