I have multiple static htmls stored in the /Content/ file. I have a method in the controller which displays these static html files.
public ActionResult GetHTML(int sectionId)
{
var result = new FilePathResult($"~/Content/files/{sectionId}.html", "text/html");
return result;
}
I have no view for this method, but I'd like to create one and to include a button which allows me to navigate to the next/previous static html.
Any help is highly appreciated.
You can create a regular view with a FilePathResult as its model.
If the model is not null in the view then you can create a hyper link in the view from result:
Next Page
Related
Desc:
I have a web tab and I need to give access to visibility
to a group of people from the database
I tried:
I am downloading a list of people for whom the bookmark must be covered
for. exp. single login: AD/ABCD
I try to send them to a partial view
and load this partial view into the layout by #Html.Action
Controller:
using ActionExecutingContext = Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext;
using ActionResult = Microsoft.AspNetCore.Mvc.ActionResult;
using Controller = Microsoft.AspNetCore.Mvc.Controller;
public class PrivilegeController : Controller
{
private readonly MembersDbContext _membersContext;
public PrivilegeController(MemebersDbContext membersDbContext)
{
_membersContext= membersContext;
}
[ChildActionOnly]
public ActionResult Header(string section)
{
var listOfManagers = _membersContext. Members.Select(x => x.Adlogin).Distinct().ToList();
ViewData["listManager"] = listOfManagers;
return PartialView("_toDevLayout");
}
}
PartialView: _toDevLayout
Layout: _TrueLayout
#Html.Action("Header", "Privilege")
what is wrong?
I got an error in my project that html.action does not exist (version mvc / core 3.1 too high)
I need to find a different solution
Cannot resolve symbol 'Action'
Hi use this in your layout page directly and use list of managers as required.
enter code here-> #{var listOfManagers = _membersContext. Members.Select(x => x.Adlogin).Distinct().ToList();}
I have table that contains data and links that open partial view with related data. I use jquery datatable, when I'm on first page everything works fine, but if I go to the next pages and cliked link I dont have beauty partial view, page return only source code from partial view file and skips _Layout.cshtml.
What should I do to make the code work correctly?
Controller:
public ActionResult KsiazkiZlecenia(int zlecKompletID, string magazynID)
{
SystemMagazynowy ksiazki = new SystemMagazynowy();
var listaksiazek = ksiazki.PobierzInfoKsiazek(zlecKompletID, magazynID);
ViewBag.ksiazki = listaksiazek;
return PartialView();
}
Link:
#Html.ActionLink("Książki", "KsiazkiZlecenia", new { zlecKompletID = item.ZlecKompletID, magazynID = ViewBag.MagazynID }, new { #data_modal = "" })
First, some context:
Language - C#
Platform - .Net Framework 4.5
Project type - ASP.Net MVC 4
I am trying to determine which View in an MVC project is handling an explicit call to the following method. The MSDN docs for the method are here: http://msdn.microsoft.com/EN-US/library/dd492930.aspx
protected internal ViewResult View(
Object model
)
The original Author is using a View to generate a PDF file with a third-party library. I need to modify the view to include additional information.
The problem: I'm having trouble finding which View to modify. There are hundreds of them, and (IMHO) they are poorly named and organized. The basic process for generating a PDF looks like this. I'm getting confused in between steps 3 and 4.
An Entity's ID is passed to an ActionResult
The Entity is retrieved from the backing store
The model is passed to the Controller.View method mentioned above:
var viewModel = View(model);
var xmlText = RenderActionResultToString(viewModel);
The resulting ViewResult is used with an instance of ControllerContext to generate HTML as if being requested by a browser.
The resulting HTML is passed to the third-party tool and converted to a PDF.
I understand everything else very clearly. What I don't understand is how the call to View(model) determines which View file to use when returning the ViewResult. Any help greatly appreciated!
I'm including the code below, in case it helps anybody determine the answer.
The ActionResult:
public ActionResult ProposalPDF(String id, String location, bool hidePrices = false)
{
var proposal = _adc.Proposal.GetByKey(int.Parse(id));
var opportunity = _adc.Opportunity.GetByKey(proposal.FkOpportunityId.Value);
ViewData["AccountId"] = opportunity.FkAccountId;
ViewData["AccountType"] = opportunity.FkAccount.FkAccountTypeId;
ViewData["Location"] = location;
ViewData["HidePrices"] = hidePrices;
return ViewPdf(proposal);
}
The ViewPDF method:
protected ActionResult ViewPdf(object model)
{
// Create the iTextSharp document.
var document = new Document(PageSize.LETTER);
// Set the document to write to memory.
var memoryStream = new MemoryStream();
var pdfWriter = PdfWriter.GetInstance(document, memoryStream);
pdfWriter.CloseStream = false;
document.Open();
// Render the view xml to a string, then parse that string into an XML dom.
var viewModel = View(model);
var xmlText = RenderActionResultToString(viewModel);
var htmlPipelineContext = new HtmlPipelineContext();
htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
//CSS stuff
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
var cssResolverPipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, pdfWriter)));
var xmlWorker = new XMLWorker(cssResolverPipeline, true);
var xmlParser = new XMLParser(xmlWorker);
xmlParser.Parse(new StringReader(xmlText));
// Close and get the resulted binary data.
document.Close();
var buffer = new byte[memoryStream.Position];
memoryStream.Position = 0;
memoryStream.Read(buffer, 0, buffer.Length);
// Send the binary data to the browser.
return new BinaryContentResult(buffer, "application/pdf");
}
The RenderActionResultToString helper method:
protected string RenderActionResultToString(ActionResult result)
{
// Create memory writer.
var sb = new StringBuilder();
var memWriter = new StringWriter(sb);
// Create fake http context to render the view.
var fakeResponse = new HttpResponse(memWriter);
var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request, fakeResponse);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), this.ControllerContext.RouteData, this.ControllerContext.Controller);
var oldContext = System.Web.HttpContext.Current;
System.Web.HttpContext.Current = fakeContext;
// Render the view.
result.ExecuteResult(fakeControllerContext);
// Restore data.
System.Web.HttpContext.Current = oldContext;
// Flush memory and return output.
memWriter.Flush();
return sb.ToString();
}
I'm not exactly sure what you're asking, but, when you call View(model) the view that is chosen is based upon conventions.
Here is an example:
public class HerbController : Controller {
public ActionResult Cilantro(SomeType model) {
return View(model)
}
}
That will look for a view file called Cilantro.cshtml in a folder called Herb (Views/Herb/Cilantro.cshtml). The framework will also look in the Shared directory as well in case it is a view that is meant to be shared across multiple results.
However, you may also want to look at the Global.asax file to see if there are any custom view paths being setup for the view engine. The example I gave above is based upon the default conventions of ASP.NET MVC. You can override them to meet your needs better if needed.
The convention for views is that they are in a folder named after the controller (without "Controller") and the .cshtml file inside that folder is named after the calling action. In your case, that should be:
~/Views/[Controller]/ProposalPdf.cshtml
The logic to determine which view template will be used is in the ViewResult that is returned from the call
var viewModel = View(model);
And how the view is selected is determined by the configured ViewEngine(s), but it will use the current Area, Controller and Action route values to determine what view should be served.
What the route values are for the ProposalPDF action will depend on how your routing is configured, but assuming the defaults, the action route value will be ProposalPDF, the controller route value will be the name of the controller class in which this action resides (minus the Controller suffix) and the area will be the area folder in which the controller lives, with a value of empty string if in the default controller folder. Then using these route values, a view will be looked up in the Views folder using the following convention
~/Views/{Area}/{Controller}/{View}.cshtml
There is always Glimpse that can help with providing runtime Diagnostics too, such as which View file was used to serve up the returned page, although I'm not sure how this would look when a ViewResult is executed internally to provide the contents of a file.
I have an ASP.NET MVC controller that generates images (they are stored in memory, I don't want to store them on the hard drive) and should return them to my view.
The problem is: I don't how know how to return multiple images from one controller method (I want to show the images in 1 view). I know that I can return a single image with the FileResult for example, but I can't find out (not on google/stackoverflow) how to return multiple images from the same method. Splitting the method up in multiple methods can't be done. Oh, all of the images are converted to a byte[], but that can be reversed if necessary.
This should work. Note I am reading my images from disk for my example but they can come from memory or anywhere. Then on the client side use java-script to display them.
[HttpGet]
public JsonResult Images()
{
var image1Base64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(Server.MapPath("~/Images/1.jpg")));
var image2Base64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(Server.MapPath("~/Images/2.jpg")));
var jsonResult = Json(new { image1 = image1Base64, image2 = image2Base64 }, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
If you have access to the MIME type of the image, you could always render them as Base64-encoded images, instead of making another request to a different controller method. This is a view model I use:
public class ImageViewModel
{
public string FileName { get; set; }
public string MIME { get; set; }
public byte[] Data { get; set; }
public override string ToString()
{
return string.Format(#"data:{0};base64,{1}", MIME.ToLower(), Convert.ToBase64String(Data));
}
}
You can use the Filename property in the alt attribute of the <img /> tag, so the markup & model-binding in your view would look something like this (assuming Razor syntax):
<img src="#model.ToString()" alt="#model.FileName" />
You do lose image-caching, AFAIK - that hasn't been an issue for me, but is understandably a deal-breaker for some.
I think that you can solve it in another way, instead of returning multiple images, you can create a utility method that loads the image in the controller
public FileContentResult GetImage(int imageId)
{
var image = GetImageById(imageId); // get from a list for example
return File(image, "image/jpeg"); // your image Mime type
}
and in the View you can do the following, iterate over the images
#foreach (var image in Model)
{
<img alt="" src="#Url.Action("GetImage", "ControllerName", new {imageId =image.Id})"/>
}
You wish to show multiple images based on input of the user, but don't want to save to the hard disk (chat). Therefor I recommand you using a session variable to save the users input in. And the use a simple FileResult to return multiple images based on that session variable.
http://blog.theobjectguy.com/2009/12/session-with-style.html
If your requirement is to show multiple images in one view it would be easier to use 2 action methods. One that returns a image with FileResult and another where you just use standard html img tags pointing the first action method
I am new to asp.net , C# and building an MVC application based on the popular Music Store application.
I have my basic navigation ready and I have reached a point where I am drawing a complete blank. Basically, my asp page displays a SQL query (which is saved in SQL DB on same machine)
Need:
I need to have a button next to this query which when clicked, connects to another DB through OLEDB, and runs the query and shows result in a pop up window.
Questions:
How do I pass the query (which is being fetched from DB) as a parameter to code below and How do I make the results pop up in a window.
Can you please point me in correct direction. The code below is from a stand alson asp page which i used for testing connections etc. basically i need to pass the query as a parameter (replacing query seen below) and have the result in a pop window.
<%# Import Namespace="System.Data.OleDb" %>
<%# Import Namespace="System.Data.Odbc" %>
<script runat="server">
sub Page_Load
Dim dbconn, sql, dbcomm, dbread
dbconn = New OleDbConnection("Provider=xxxx;Password=xxxx;User ID=xxxx;Data Source=xxxx;Initial Catalog=xxxx;Port=xxxx;")
dbconn.Open()
sql = "Select ID from TABLE1"
dbcomm = New OleDbCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader() <%-- Call this method within oledbcommand--%>
If dbread.Read = False Then
MsgBox("No Data Check")
Else
Response.Write("<table>")
Do While dbread.Read()
Response.Write("<tr>")
Response.Write("<td>")
Response.Write(dbread(0))
Response.Write("</td>")
Response.Write("</tr>")
Loop
Response.Write("</table>")
End If
dbconn.Close()
end sub
</script>
ADDITIONAL DETAILS
CONTROLLER CLASS
.
.
public ActionResult DisplayResult(String Qry)
{
List<QuerySet> QueryToExecute = new List<QuerySet>();
return View(QueryToExecute);
VIEW that provides this contoller with DATA, this is query that is fetched from my SQL DB and should be executed to a separate DB on a separate server.
<ul>
#foreach (var ShowQueries in Model.Queriess)
{
<li>
#Html.ActionLink(ShowQueries.Query, "DisplayResult", new { Qry = ShowQueries.Query })
</li>
}
ISSUE:
How should I use a view named 'DisplayResult' which handles the query fetched by view above and executes it agaisnt another DB.
I was hoping I can use a Webform view rather than a razor view but either way i am not able to pass the parameter
Any ideas are appreciated
The point of MVC is to move data connections out of the View (aspx page) and into a Controller.
Read some more MVC tutorials, and buy a book or two. You should actually populate the data into a viewmodel on the controller, and then pass that viewmodel to the view. This way, the view knows nothing about how to get the data -- it already got it from the controller.
Views should have the responsibility of displaying data to users over the web, not getting the data or manipulating it directly.
With that aside, here is how you would do it:
Pass the query as a string to an Action Method on a Controller (using HTTP POST or GET) using AJAX (i.e. jQuery $.ajax() method).
Have the action method return the HTML for your popup window, using a Partial View. You could also return Json, but I think HTML / partial view would be easier in this case. This is the method that will do your OLE DB connection, and execute the query.
In your $.ajax() success function callback, write javascript that will popup a new dialog with the partial view HTML that was returned by the controller action method.
You could create a class to hold the data you want to display:
namespace sample {
class viewList
{
public string field1 {get;set;}
...
}
}
and create a list to hold your results in your controller:
List<viewList> theList = new List<viewList>();
//Populate dbread here...
while (dbread.Read())
{
viewList listData = new viewList();
listData.field1 = (dataType)dbread[0]; //Convert to your data type
theList.Add(listData);
}
and pass this to the view:
return view(theList);
Then in your model (of model type viewList) display your results in a table:
#model sample.viewList
<table>
#foreach (var item in Model)
{
<tr>
<td>#item.field1</td>
</tr>
}
</table>
ALTERNATIVE
To display in popup, put the list into the ViewBag like this:
List<viewList> theList = new List<viewList>();
//Populate dbread here...
while (dbread.Read())
{
viewList listData = new viewList();
listData.field1 = (dataType)dbread[0];
theList.Add(listData);
}
ViewBag.Items = theList;
Then in your view:
<script type="text/javascript">
$(function() {
var array = #Html.Raw(Json.Encode(ViewBag.Items));
//Construct your table using the array here...
alert(theConstructedTable);
});
</script>