I have this sample code from different sources and I want to try it first before applying it to my code which is pretty similar to the samples I got.
I have the following codes in my controller:
[Route("getcsv")]
[HttpGet]
public HttpResponseMessage GetCSV()
{
var data = new[]{ //Suppose you filter out these data
new{ Name="Ram", Email="ram#techbrij.com", Phone="111-222-3333" },
new{ Name="Shyam", Email="shyam#techbrij.com", Phone="159-222-1596" },
new{ Name="Mohan", Email="mohan#techbrij.com", Phone="456-222-4569" },
new{ Name="Sohan", Email="sohan#techbrij.com", Phone="789-456-3333" },
new{ Name="Karan", Email="karan#techbrij.com", Phone="111-222-1234" },
new{ Name="Brij", Email="brij#techbrij.com", Phone="111-222-3333" }
};
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(WriteTsv(data));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); //attachment will force download
result.Content.Headers.ContentDisposition.FileName = "RecordExport.csv";
return result;
}
public string WriteTsv<T>(IEnumerable<T> data)
{
StringBuilder output = new StringBuilder();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in props)
{
output.Append(prop.DisplayName); // header
output.Append("\t");
}
output.AppendLine();
foreach (T item in data)
{
foreach (PropertyDescriptor prop in props)
{
output.Append(prop.Converter.ConvertToString(
prop.GetValue(item)));
output.Append("\t");
}
output.AppendLine();
}
return output.ToString();
}
I am calling this method through the following:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function save() {
window.open('https://localhost:44370/api/values/getcsv', '_blank', '');
}
</script>
</head>
<body>
<a class="btn btn-primary" onclick="save()">Export</a>
</body>
</html>
All of these give me the following result instead of downloading a file:
I don't have any idea what I am missing. Please help! Thank you!
You are most likely using the wrong syntax for your version of Web API.
If using Asp.Net Core Web API it would need to be refactored to
[Route("api/[controller]")]
public class ValuesController: Controller {
//GET api/values/getcsv
[Route("getcsv")]
[HttpGet]
public IActionResult GetCSV() {
var data = new[]{ //Suppose you filter out these data
new{ Name="Ram", Email="ram#techbrij.com", Phone="111-222-3333" },
new{ Name="Shyam", Email="shyam#techbrij.com", Phone="159-222-1596" },
new{ Name="Mohan", Email="mohan#techbrij.com", Phone="456-222-4569" },
new{ Name="Sohan", Email="sohan#techbrij.com", Phone="789-456-3333" },
new{ Name="Karan", Email="karan#techbrij.com", Phone="111-222-1234" },
new{ Name="Brij", Email="brij#techbrij.com", Phone="111-222-3333" }
};
var bytes = System.Text.Encoding.UTF8.GetBytes(WriteTsv(data));
return File(bytes, "application/octet-stream", "RecordExport.csv");
}
//...code omitted for brevity
}
In Asp.Net Core HttpResponseMessage is no longer treated as a first class citizen of the pipeline and is being serialized like a normal model.
Related
I try to send a list of object to controller but controller always receives it as null.
var model= #Html.Raw(Json.Encode(Model.MultipleElements));
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: '#Url.Action("AddField", "Flux")',
data: model,
success: function (response) {
$(".destinationMultiple").html(response);
}
});
And here is my controller action
public PartialViewResult AddField(List<Destination> model)
{
return PartialView("_myPartialView");
}
You can use Ajax.Beginform. If you want you can do the following, which explains how to pass arrays from View to Controller.
View/Controller
namespace Testy20161006.Controllers
{
public class Destination
{
public string aDestination { get; set; }
}
public class TahtohViewModel
{
public List<Destination> MultipleElements { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public PartialViewResult AddField(List<Destination> MultipleElements)
{
List<String> sendout = new List<string>();
foreach (Destination dest in MultipleElements)
{
sendout.Add(dest.aDestination);
}
ViewBag.SendoutList = sendout;
return PartialView("_myPartialView");
}
public ActionResult Tut149()
{
Destination dest1 = new Destination { aDestination = "adest1" };
Destination dest2 = new Destination { aDestination = "adest2" };
Destination dest3 = new Destination { aDestination = "adest3" };
TahtohViewModel tahtoViewModel = new TahtohViewModel { MultipleElements = new List<Destination>() };
tahtoViewModel.MultipleElements.Add(dest1);
tahtoViewModel.MultipleElements.Add(dest2);
tahtoViewModel.MultipleElements.Add(dest3);
return View(tahtoViewModel);
}
View
#model Testy20161006.Controllers.TahtohViewModel
#using Testy20161006.Controllers
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut149</title>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
var items = [];
var q = $("input[name='theElemsName']");
$.each(q, function (index, thevalue) {
var item = {};
item.aDestination = thevalue.value;
items.push(item);
});
jQuery.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("AddField", "Home")',
data: JSON.stringify(items),
success: function (response) {
//alert("success");
$(".destinationMultiple").html(response);
}
});
})
})
</script>
</head>
<body>
<div>
<table>
#{ var index = 0;}
#foreach (Destination item in Model.MultipleElements)
{
<tr><td>Item <span>#(index++)</span></td><td data-multipleelements="#(index)">#Html.TextBox(item.aDestination, null, new { Name = "theElemsName", Value = item.aDestination })</td></tr>
}
</table>
<input type="button" id="theButton" value="Add Field" />
<div class="destinationMultiple"></div>
</div>
</body>
</html>
Partial View
my partial view
#foreach (string item in ViewBag.SendoutList)
{
<div>#item</div>
}
I want to pass selected Drop down list value to Ajax Action Link which is I am using in Controller. Every time When I will change drop down list value. I want that respective value pass to the action link.
What I need to write here in Ajax Action Link ????
Drop Down List
<div class="form-group">
#Html.DropDownListFor(model => model.ComponentId, ((List<string>)ViewBag.Cdll).Select(model => new SelectListItem { Text = model, Value = model }), " -----Select Id----- ", new { onchange = "Action(this.value);", #class = "form-control" })
</div>
Ajax Action Link
<div data-toggle="collapse">
#Ajax.ActionLink("Accessory List", "_AccessoryList", new { ComponentId = ???? }, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "divacc",
InsertionMode = InsertionMode.Replace
})
</div>
Controller
public PartialViewResult _AccessoryList(string ComponentId)
{
List<ComponentModule> li = new List<ComponentModule>();
// Code
return PartialView("_AccessoryList", li);
}
Here is a new post. I do dropdowns a little different than you, so I am showing you how I do it. When you ask what to pass, I am showing you how to pass the dropdown for 'component' being passed. I also show how to pass from ajax back to the page.
Controller/Model:
//You can put this in a model folder
public class ViewModel
{
public ViewModel()
{
ComponentList = new List<SelectListItem>();
SelectListItem sli = new SelectListItem { Text = "component1", Value = "1" };
SelectListItem sli2 = new SelectListItem { Text = "component2", Value = "2" };
ComponentList.Add(sli);
ComponentList.Add(sli2);
}
public List<SelectListItem> ComponentList { get; set; }
public int ComponentId { get; set; }
}
public class PassDDLView
{
public string ddlValue { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostDDL(PassDDLView passDDLView)
{
//put a breakpoint here to see the ddl value in passDDLView
ViewModel vm = new ViewModel();
return Json(new
{
Component = "AComponent"
}
, #"application/json");
}
public ActionResult IndexValid8()
{
ViewModel vm = new ViewModel();
return View(vm);
}
View:
#model Testy20161006.Controllers.ViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid8</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnClick").click(function () {
var PassDDLView = { ddlValue: $("#passThis").val() };
$.ajax({
url: '#Url.Action("PostDDL")',
type: 'POST',
data: PassDDLView,
success: function (result) {
alert(result.Component);
},
error: function (result) {
alert('Error');
}
});
})
})
</script>
</head>
<body>
<div class="form-group">
#Html.DropDownListFor(m => m.ComponentId,
new SelectList(Model.ComponentList, "Value", "Text"), new { id = "passThis" })
<input type="button" id="btnClick" value="submitToAjax" />
</div>
</body>
</html>
Does anyone has a clean suggestion of instantiate this jquery's useful library.
I need to submit files and manage the Json response from the server.
I always get none json response within the Js code. I have reviewed some articles mentioning it but the code doesn't fit to the purpose.
The situation is: I achieve the submition and saving in the database but the Json response never arrives.
Thanks in advance.
This is my view code:
<script type="text/javascript">
$("#formUplImg").fileupload({
dataType: "json",
url:'#Url.Action("CreateJson","ProductImage")',
done: function (e, data) {
alert(data.StatusMessage);
}
});
</script>
#using (Html.BeginForm("CreateJson", "ProductImage", FormMethod.Post, new { id = "formUplImg", enctype = "multipart/form-data", #class = "jqtransform" }))
{
#Html.ValidationSummary(true)
<div class="rowElem">
<input type="file" id="Content" name="Content" />
</div>
<div class="rowElem">
#Html.ValidationMessageFor(item => item.Content)
</div>
<div class="rowElem">#Html.JQueryUI().Button("Guardar imagen", ButtonElement.Button, ButtonType.Submit, new { id = "guardar_imagen" })</div>
}
This is my controller action code:
[HttpPost]
public ContentResult CreateJson(UploadedFileInfo fileInfo)
{
try
{
if (fileInfo.Content == null)
throw new Exception("Hubo problemas con el envĂo. Seleccione un archivo a subir");
var file = new TempDocument
{
CreatedBy = User.Identity.Name,
CreationTime = DateTime.Now,
FileName = fileInfo.Content.FileName,
MimeType = fileInfo.Content.ContentType,
Size = fileInfo.Content.ContentLength,
Content = new byte[fileInfo.Content.ContentLength]//Image content to save
};
fileInfo.Content.InputStream.Read(file.Content, 0, fileInfo.Content.ContentLength);//Reading image content into ProductImage object
DocumentsManager.StorePendingDocuments.Add(file);
DocumentsManager.SaveTempDocuments();//Store each document uploaded to: TempDocument Table
TempData["SuccessMsg"] = "The image was saved successfully";
var json = new JavaScriptSerializer().Serialize(new { Success = true, StatusMessage = "El objeto fue insertado correctamente" });
return Content(json, "application/json");
}
catch (Exception exception)
{
TempData["ErrorMsg"] = exception.Message;
var json = new JavaScriptSerializer().Serialize(new { Success = false, StatusMessage = exception.Message });
return Content(json, "application/json");
}
}
Use return type of Action as ActionResult and use:
`return Json(new { Result = "Success" });`
So that on success you will get Json object containing result value.
HI all i have some images which i am retrieving dynamically and displaying in a view like this
here is my controller
private ProductEntities products = new ProductEntities();
public List<ProductItems> GetAllProducts()
{
var items = new List<ProductItems>();
var records = products.Products.ToList();
foreach (var item in records)
{
ProductItems model = new ProductItems();
model.ProductID = item.ProductId;
model.ProductName = item.ProductName;
model.ImageURL = item.ImageURL;
items.Add(model);
}
return items;
}
and this is my index page view
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/api/ProductDetails", function (data) {
$.each(data, function (idx, ele) {
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
$("#makeMeScrollable").append('<h4>' + ele.ProductName + '</h4>');
});
});
});
</script>
</head>
<body>
<h1>Products</h1>
<div class="rightsection_main">
<div class="img_main" id="makeMeScrollable">
</div>
</div>
</body>
now what i want is when ever an user clicks on a image i have to pass the ID of the image to my method in my apicontroller and i have to display that image in another view ..how do i pass my image to another view and Id to my api/controller action
i have to pass my ProductID to this method
public IEnumerable<ProductItems> ProductDeatils(long ProductID)
{
var productdeatils = products.ExecuteStoreQuery<ProductItems>("GetProductDetail #ProductID ", new SqlParameter("#ProductID", ProductID));
return productdeatils ;
}
The thing is that API actions do not return views. They are used to serialize models using some format such as JSON or XML. So when you are saying that you want to use the ProductDeatils API action to display a view, this doesn't make much sense. Views are returned by standard ASP.NET MVC controller actions returning ActionResults. So let's see how to set this up.
Let's suppose that you have the following API controllers:
public class ProductsController : ApiController
{
private ProductEntities products = new ProductEntities();
public IEnumerable<ProductItems> Get()
{
return products.Products.ToList().Select(item => new ProductItems
{
ProductID = item.ProductId,
ProductName = item.ProductName,
ImageURL = item.ImageURL
});
}
}
public class ProductDetailsController : ApiController
{
private ProductEntities products = new ProductEntities();
public ProductItems Get(long id)
{
return products.ExecuteStoreQuery<ProductItems>(
"GetProductDetail #ProductID ",
new SqlParameter("#ProductID", id)
);
}
}
Alright, now we will need standard ASP.NET MVC controller that will serve the views:
public class HomeController : Controller
{
public ActionResult Products()
{
return View();
}
public ActionResult ProductDetail(long id)
{
using (var client = new HttpClient())
{
var productDetailUrl = Url.RouteUrl(
"DefaultApi",
new { httproute = "", controller = "productdetails", id = id },
Request.Url.Scheme
);
var model = client
.GetAsync(productDetailUrl)
.Result
.Content
.ReadAsAsync<ProductItems>()
.Result;
return View(model);
}
}
}
and the respective view for showing the list of products and the detail of a product when a link is clicked:
~/Views/Home/Products.cshtml:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h1>Products</h1>
<div class="rightsection_main">
<div class="img_main" id="makeMeScrollable">
</div>
</div>
<script type="text/javascript" src="~/scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
var productsUrl = '#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "products" })';
var productDetailUrl = '#Url.Action("productdetail", "home", new { id = "__id__" })';
$.getJSON(productsUrl, function (data) {
$.each(data, function (idx, product) {
$('<img/>').attr({ src: product.ImageURL }).appendTo('#makeMeScrollable');
$('#makeMeScrollable').append(
$('<h4/>').html(
$('<a/>', {
href: productDetailUrl.replace('__id__', product.ProductID),
text: product.ProductName
})
)
);
});
});
</script>
</body>
</html>
and ~/Views/Home/ProductDetail.cshtml:
#model ProductItems
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ProductDetail</title>
</head>
<body>
<h4>#Html.DisplayFor(x => x.ProductName)</h4>
<img src="#Model.ImageURL">
</body>
</html>
I'm having some problems publishing an asp.net mvc3 application. When deployed, the application fails with "The controller for path '/Dashboard/Alarmes' was not found or does not implement IController" where Alarmes is an action at DashboardController. Not sure if it has something to do with it, but Alarmes return an Json result.
Another thing I noticed is that some assemblies, that are referenced by another project in the same solution, are not deployed (only if I reference them in the mvc project itself).
Any tips on these?
Update:
The routes registration:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*allpng}", new { allpng = #".*\.png(/.*)?" });
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.IgnoreRoute("{directory}/{resource}.asmx/{*pathInfo}");
routes.MapRoute("Default", "{controller}/{action}/{id}", new {
controller = "Dashboard",
action = "Index",
id = UrlParameter.Optional
});
}
the action:
public ActionResult Alarmes() {
var alarmesPorPonto = new Dictionary<string, List<Ponto>>();
var alarmes = _repositorioDeAlarmes.Pesquise(ObtenhaInicio(), DateTime.Today);
foreach (var alarme in alarmes) {
var tipo = alarme.Tipo;
var ponto = alarme.Ponto;
if (!alarmesPorPonto.ContainsKey(tipo.Nome)) {
alarmesPorPonto.Add(tipo.Nome, new List<Ponto>());
}
if (!alarmesPorPonto[tipo.Nome].Contains(ponto)) {
alarmesPorPonto[tipo.Nome].Add(ponto);
}
}
return Json(alarmesPorPonto.Select(a => new { Tipo = a.Key, a.Value.Count }), JsonRequestBehavior.AllowGet);
}
Another missing info: I'm deploying this application to a virtual directory.
Update 2
the full controller class:
public class DashboardController : Controller {
private readonly IRepositorioDeAlarmes _repositorioDeAlarmes;
private readonly bool _enableMap;
public DashboardController(IRepositorioDeAlarmes repositorioDeAlarmes) {
_repositorioDeAlarmes = repositorioDeAlarmes;
_enableMap = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableMap"]);
}
public ActionResult Index() {
ViewBag.EnableMap = _enableMap;
return View();
}
public ActionResult Alarmes() {
var alarmesPorPonto = new Dictionary<string, List<Ponto>>();
var alarmes = _repositorioDeAlarmes.Pesquise(ObtenhaInicio(), DateTime.Today);
foreach (var alarme in alarmes) {
var tipo = alarme.Tipo;
var ponto = alarme.Ponto;
if (!alarmesPorPonto.ContainsKey(tipo.Nome)) {
alarmesPorPonto.Add(tipo.Nome, new List<Ponto>());
}
if (!alarmesPorPonto[tipo.Nome].Contains(ponto)) {
alarmesPorPonto[tipo.Nome].Add(ponto);
}
}
return Json(alarmesPorPonto.Select(a => new { Tipo = a.Key, a.Value.Count }), JsonRequestBehavior.AllowGet);
}
}
I suspect that you have hardcoded the url in your javascript when invoking the action instead of using an url helper.
So you wrote:
<script type="text/javascript">
$.getJSON('/Dashboard/Alarmes', function(result) {
...
});
</script>
instead of:
<script type="text/javascript">
$.getJSON('#Url.Action("Alarmes", "Dashboard")', function(result) {
...
});
</script>
which would have generated the correct url in the case when your application is hosted in a virtual directory which would be:
<script type="text/javascript">
$.getJSON('/MyAppName/Dashboard/Alarmes', function(result) {
...
});
</script>
What if you try to clean the ASP.Net temporary files and restart the web server?
[{windows-path}\Microsoft.NET\Framework{framework-version}\Temporary ASP.NET Files]