I want to let user download data I am displaying elsewhere in the website as reports.
I am using Asp.net core 2.1 rc1 MVC app.
My cunning plan was to create a special view which would render data as a tab delimited text and use response headers to make browser download it instead of displaying HTML. This almost works perfectly.
My "HttpGet" code in the controller looks like this:
Response.Headers.Add("Content-disposition", "attachment; filename=export.tsv");
return View(MyModel);
My razor view looks like this:
#Model IEnumerable<MyModel>
#{
Layout = null;
String LineBreak = Environment.NewLine;
String Tab = "\t";
}
Header1 Header2 ...
#if (Model.Count > 0)
{
foreach (MyModel myModel in Model)
{
#myModel.Field1#Html.Raw(#Tab)#myModel.Field2 ... #Html.Raw(#LineBreak)
}
}
This works splendidly except that this ugly error message appears as a first line in the file:
System.Collections.Generic.List`1[MyApp.Models.MyModel] IEnumerable<MyModel>
The rest of the file is exactly what I need.
Does anyone know how to remove this message? Or if there is something wrong with my general approach...
Full project available here: https://github.com/under3415/ExportError/ (just click on download link and examine the file)
You've written #Model, while the correct syntax is #model (lowercase - it's case-sensitive).
A first-line #model directive specifies the model type. #Model dereferences the actual model instance. What you're seeing is its ToString representation.
You're getting this error because you're returning view with the model return View(MyModel);, you should be using FileResult
Here are the complete instructions on it
Download file of any type in Asp.Net MVC using FileResult?
Related
I want get a content of html file using C# and the pass those into cshtml view page. is this possible to do ?
my main requirement is load a html file into TinyMCE editor content, which is located at another destination.
but once I explore about this I saw given answers like below
You cannot give a path to the setContent function directly. What you need to do is to get the html file contents backendside and send it to your page where you insert it into your editor using the setContent method.
but I dont know how to get the html file content and send it to page in asp.net mvc
However I tried like below to insert html file using jquery
setup: function(ed) {
ed.on("init", function(ed) {
$.get("myhtml.html", function (content) {
tinyMCE.activeEditor.setContent(content);
});
})}
but this once also not working for me. any suggestion would be highly appreciate
This is very simple. Instead of using it from the jQuery i'll suggest to create the MVC controller action with string return type and then use File.ReadAllText method of System.IO assembly to get the content of the html file.
public class HomeController : Controller {
public IHtmlString TyneMice()
{
return new MvcHtmlString(System.IO.File.ReadAllText("filename"));
}
}
you can call this controller and action from jQuery.
I hope this answer helps you. If you need more detail on how to read the content from html file you can find here
I am creating a dynamic menu depending on the user role in MVC C#, and (while I can load the HTML tags) the Action links in the menu are not rendering. I imagine this is due to the # at sign at the beginning:
if(userGroup.Equals("Administrators")){
menuItems+=#"<span class=""menuItem"">
#Html.ActionLink(""Add User"", ""RegisterNewUser"", ""Home"", null, new{#Class=""menuItemActionLink""})
</span>";
}
(...)
ViewData["menuItems"]=menuItems;
With a view retrieval:
#Html.Raw(#ViewData["menuItems"])
I have attempted variations of html encoding to no avail. The best solution I can think of is to use the at sign escape code, but I do not know what it is (I tried '\' as well as concatenation in the form of "#" + #"Html.ActionLink). Any ideas?
While I'm not sure why exactly it is that the actionlink is not being rendered properly (maybe the upper-case C in class?), the practice of sending html from the controller to the view is not a good idea. This conflates the roles of controller and view, and makes it more difficult for anyone expecting the distinction between these entities.
A better option might be to have a code block in the view such as:
#if (ViewData["admin"] != null){ ...code to render your admin menu ... }
and in your controller:
if(userGroup.Equals("Administrators")){ ViewData["admin"] = true; }
Depending on your needs, these snippets may change. You could test for true or false (instead of null), or add a string; the ViewData is pretty much what you make of it. But this at least maintains the distinction between HTML rendering at the View and process control at the controller.
#if(userGroup.Equals("Administrators")) {
menuItems += "<span class=\"menuItem\">" + Html.ActionLink("Add User", "RegisterNewUser", "Home", null, new { #class = "menuItemActionLink" }) + "</span>";
}
I am learning ASP.Net MVC 4 Programming. Currently, I want to display the list of files to the web page. Following is what I did till now.
In the HomeController.cs I edited the Contact action as follows:
public ActionResult Contact()
{
ViewBag.Message = "Your file page.";
DirectoryInfo dirInfo = new DirectoryInfo(#"c:\");
List<string> filenames=dirInfo.GetFiles().Select(i=>i.Name).ToList();
ViewBag.data = filenames;
///^^ Is this correct??
return View();
}
I want the filenames to be displayed to the web page. What should I write in my view? I right clicked the Contact action and got the default view, containing:
#{
ViewBag.Title = "Contact";
}
<h2>Contact</h2>
As #ChrisV wrote, you may want to create a strongly typed view. That means that you're associating a Model with your View. You would then pass the data using the View() overload which takes the Model as parameter. In your current version, you're sending data to the view using the ViewBag. That's not wrong, but it would be probably best to create a strongly typed view, at least as you go along learning.
That being said, I would probably do the following changes:
In your controller, get a list of FileInfo objects, instead of file names. The FileInfo type exposes additional features that you can use to enrich the displayed data.
public ActionResult Contact()
{
ViewBag.Message = "Your file page.";
DirectoryInfo dirInfo = new DirectoryInfo(#"c:\");
List<FileInfo> files = dirInfo.GetFiles().ToList();
//pass the data trough the "View" method
return View(files);
}
Next, you need to specify the model type inside your view, and to iterate and display the data:
#model IEnumerable<FileInfo>
#{
ViewBag.Title = "Contact";
}
<h2>Contact</h2>
<ul>
#foreach (FileInfo file in Model)
{
<li>#file.Name</li>
}
</ul>
Please note, what and how you actually display on the page is up to you. You could create a table for the files and display the creation time, the size or even a command (download, delete, etc.). This is just a "template"; use it as such.
The primary thing you are displaying on the page (i.e. what the view is "for") should be the model. Look up the #model directive. Here it should be #model List<string>. Then instead of setting ViewBag.data, use return View(filenames);. In your view you will then be able to access a strongly-typed model. If there's anything you don't understand about what I just said, you need to read more about the role of a viewmodel in ASP.NET MVC.
I built a console application in Visual Studio 2013, that sends email reports daily. I am using a .cshtml template parsed with Razor.
Is it possible to use partial views for my main cshtml file?
I tried using the syntax:
#Html.Partial("_partial")
but I get an error ("The name 'Html' does not exist...").
I found information about partial views only with MVC projects. I want to know how and if I can use them in a console application.
I also tried to render the partial view, to a string inside the cshtml main template, but my template will read html markup as literal string. And I can't seem to use HTML helpers outside of MVC.
Thank you in advance.
You will need to reference System.Web.Mvc.Html and then set the template base.
Razor.SetTemplateBase(typeof(HtmlTemplateBase<>));
I resolved this issue and I will post answer here, in case there are others that would benefit.
I implemented the Partial method that would render the partial view, and then set the new template base.
public class ExtendedTemplateBase<TModel> : TemplateBase<TModel>
{
public string Partial<TPartialModel>(string path, TPartialModel model)
{
var template = File.ReadAllText(path);
var partialViewResult = Razor.Parse(template, model);
return partialViewResult;
}
}
I am calling a Controller Action from a view, within that controller I need to invoke another Action which I will invoke to save the view to a network location as either HTML or Image.
How do I retrieve the URL to an Action from within a Controller. Please note I need the actual URL, this means RedirectionToAction or View() wont work.
Why? I need to pass in a URL which will contain a call to a View. This view will be used to generate an image or HTML document using the System.Windows.Forms.WebBrowser.
.NET 3.5; C#; MVC 1;
I could do something like this, but its dirty ... well it leaves me with that dirty feeling.
using(Html.BeginForm("Action", "MyWorkflowController",
new {
MyId = "bla",
URLToGenerateImage = Url.Action("GenerateImage", "MyWorkflowController")
}))
I ended up using the MvcContrib.UI.BlockRenderer to convert to View to Html instead of generating the image. I proceeded to save the html string to a file system location.
Here is a link for further information
http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvc/
How about ContentResult - Represents a text result, so you could have
/Controller/GetUrl/id
Public ActionResult GetUrl(int id)
{
// builds url to view (Controller/Image/id || Controller/Html/id)
var url = BuildImageUrl(id);
return ContentResult(url);
}
in view you could have:
GenerateImage