I need to use &mdash (more beautiful as par my UI/UX designer), instead of regular '-' .
My question is how do I jam this html dash &mdash inside my controller where I am setting my pageHeading and BrowserTitle.
I am working with an MVC application, the code below is the controller which gets the result and then bundles up and sends it to the view.
In the View the PageHeading comes up automatically:
public ActionResult View()
{
var dto = _service.GetByID(id);
base.BrowserTitle = "Reports - " + report.ReportDisplayName;
base.PageHeading = "Reports - " + report.ReportDisplayName;
return View(dto);
}
Related
Q) How do I access my website content, e.g. books collection in my WebAPI class?
In an Umbraco 8 website project, I am using the following in my razor view to get content, which works fine, allowing me to then iterate over the collection and build my page, all great.
#inherits Umbraco.Web.Mvc.UmbracoViewPage
#using ContentModels = Umbraco.Web.PublishedModels;
#using System.Text.RegularExpressions;
#{
var books = Model.Root().DescendantsOfType("Book")
.Cast<Book>().Where(x => x.ShowInWebsite);
}
//...
However, this doesn't compile in my WebAPI class - I don't know how to fix the references needed.
Error I'm getting:
The name 'Model' does not exist in the current context
Other things I've tried:
var books = Umbraco.ContentAtRoot().DescendantsOrSelf().OfTypes("Book");
// Which gives error:
IEnumerable<IPublishedContent>' does not contain a definition for 'DescendantsOrSelf' and the best extension method overload 'PublishedContentExtensions.DescendantsOrSelf(IPublishedContent, string)' requires a receiver of type 'IPublishedContent
You WebApi class doesn't have a model, but as long as it inherits from UmbracoApiController you should be able to do
Umbraco.ContentAtRoot()...
instead?
https://our.umbraco.com/documentation/reference/routing/webapi/
According to https://our.umbraco.com/documentation/Reference/Querying/IPublishedContent/Collections/#oftypes you should then be able to do
Umbraco.ContentAtRoot().DescendantsOrSelf().OfTypes("Book")
Thanks to the comment by #Jannik Anker
I managed to get my collection by so:
var parent = Umbraco.ContentAtRoot().First().Children().FirstOrDefault(x => x.Name == "Booklist");
if (parent != null)
{
var books = parent.Children();
var test = "";
foreach (var book in books)
{
test += book.Id + ": " + book.Name + "\r\n";
}
return test;
}
I have a function in my View called DisplayImage() that works great
#foreach (var x in Model)
{
#Html.Raw(#DisplayImage(x.FrontFileName))
}
#functions {
public static string DisplayImage(string bagname)
{
string img = "http://www.airsicknessbags.com/images/" + bagname + ".jpg";
string result = "<a href=" + img + " target=\"_blank\">";
result += "<img src=" + img + " style=\"width: 100px\" />";
result += "</a>";
return (result);
}
}
Another page also needs DisplayImage. Instead of duplicating the code in each View, how do I put (and call) the code from a single place?
I've seen that you can do this with HTML helpers in the App_Code directory of earlier versions of MVC, but I'm using .net Core 3.1. I've tried RenderSection in both the _Layout.cshtml and in my View page, but I can't seem to get it right.
I am trying to create new view using Asp.Net MVC. My view created successfully along with respective changes in my controller but
it shows 404 error as the view is not included in project.
After including if I am trying to run this and hit url/controller/Action its working perfectly.
My code is as follows for creating view and adding action in controller
// My main aim is to create new page dynamically
[HttpPost]
public ActionResult Index(Content model)
{
var fileName = model.Name; // validate to check the same name don't exist.
if (!System.IO.File.Exists(fileName))
{
System.IO.File.Create(Server.MapPath("~/Views/Custom/"+fileName+".cshtml"));
}
//start Append data in custom controller
var lines = System.IO.File.ReadAllLines(Server.MapPath("~/Controllers/CustomController.cs"));
System.IO.File.WriteAllLines((Server.MapPath("~/Controllers/CustomController.cs")), lines.Take(lines.Length - 2).ToArray());
//start Append data in custom controller
//System.IO.File.WriteAllLines((Server.MapPath("~/Controllers/CustomController.cs")), "public ActionResult'" + fileName + "'(){");
string appendData = "public ActionResult "+ fileName+ "() \n { \n";
appendData += "return View();";
appendData += " \n } \n } \n }";
System.IO.File.AppendAllText((Server.MapPath("~/Controllers/CustomController.cs")), appendData);
objcontext.objContent.Add(model);
objcontext.SaveChanges();
ModelState.Clear();
return View();
}
Please help me how to include the file dynamically where I don't need to do manual include.
You can achieve dynamic controller by loading Assembly during execution. But writing a cs class, it won't work.
Have a look at below approach
http://www.strathweb.com/2012/06/using-controllers-from-an-external-assembly-in-asp-net-web-api/
Say I have two different controllers i.e. Controller A and Controller B. How can I access Detail Action of Controller A from PartialView of Controller B.
I tried by javascript
document.location = '#Url.Action("Detail", "Controller A")' + "/#id=" + id; OR
windows.location = '#Url.Action("Detail", "Controller A")' + "/#id=" + id;
But its not working. is it a valid scenario?
The way you passing id if it is a action parameter is wrong, it should be like this -
document.location = "#Url.Action("Detail", "Controller A", new {id = "_Id"})".replace("_Id", id);
I found the following answer from Darin Dimitrov - In ASP MVC3, how can execute a controller and action using a uri?
var routeData = new RouteData();
// controller and action are compulsory
routeData.Values["action"] = "index";
routeData.Values["controller"] = "foo";
// some additional route parameter
routeData.Values["foo"] = "bar";
IController fooController = new FooController();
var rc = new RequestContext(new HttpContextWrapper(HttpContext), routeData);
fooController.Execute(rc);
The only problem is that I like to capture the ViewResult that is returned by this Action (to render it as a string), but IController.Execute returns void.
I suspect I can find the Result somewhere in the property of the ControllerContext, but I can't find anything like that. Does anyone have an idea how to do this?
What you want to do, as far as I understand is to actually render the view, get the HTML result and assert against it.
This is practically testing the view which is pretty much not recommended and against most practices.
However, you could come up with some solutions to this. The one presented (simplified and a bit messy) is using RazorEngine to render the view. Since you can't get access to the .cshtml (the view file) from the test project you will need to get to its contents in a messy way.
Install RazorEngine NuGet package to your test project and try something along these lines:
[Fact]
public void Test()
{
var x = new HomeController(); // instantiate controller
var viewResult = (ViewResult)x.Index(); // run the action and obtain its ViewResult
var view = string.IsNullOrWhiteSpace(viewResult.ViewName) ? "Index" : viewResult.ViewName; // get the resulted view name; if it's null or empty it means it is the same name as the action
var controllerName = "Home"; // the controller name was known from the beginning
// actually navigate to the folder containing the views; in this case we're presuming the test project is a sibling to the MVC project, otherwise adjust the path to the view accordingly
var pathToView = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace("file:\\", "");
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.Combine(pathToView, "WebApplication5\\Views\\" + controllerName + "\\" + view + ".cshtml");
var html = Razor.Parse(File.ReadAllText(pathToView), viewResult.Model); // this is the HTML result, assert against it (i.e. search for substrings etc.)
}