Dynamically display welcome string in "Your logo here" - c#

What I am trying to do is to dynamically display welcome string of the company name based on url the area of "Your logo here" in MVC 4 Internet applcation.
So if I am in http://aaa.com I wanna to say welcome to aaa
What I have done is to replace
<p class="site-title">#Html.ActionLink("your logo here", "Index", "Home")</p>
to
#Html.Partial("_Company")
and in the _Company view I do #Html.RenderAction( "Company", "Home")
and in the HomeController I use
public ActionResult HospitalInfo()
{
var url = GetUrlMethod();
return PartialView("_Company ", new { name = url });
}
Can anyone please let me know if my idea is correct or not ? or can you help me to improve the method. Currently, my code does not work at all...

If you're only interested in a string, you don't need to spin up a separate partial view with its own controller action. Just create a helper function, manipulate the URL in there, and then call the function directly from your View.
.cs:
public static string GetCustomWelcomeString()
{
string customString;
// use System.Web.HttpContext.Current.Request.Url here to do the cool stuff
return customString;
}
.cshtml:
<p class="site-title">#MyClass.GetCustomWelcomeString()</p>
For a more architecturally clean solution, consider pre-calculating this title in the main controller action and returning it as a model field, so the view can consume it directly using #Model.CustomWelcomeString or something like that..

Try using the request object:
<p>Host is #Request.Url.Host</p>
You can split the URL however you want, but it doesn't need to go to the controller to get it

I ended up to use #ViewBag.CompanyName and created a base controller which all other controllers inherated from. And create a action method in which passing the company name string into #ViewBag.CompanyName.
So far so good.

Related

ASP.NET MVC - How do I Call a Controller Method from within a View to Redirect to Multiple Other Views?

I am trying to add a single link in my navbar that redirects the user to a different webpage depending on their account type. I am having issues doing this and could use some help.
The Controller code that I am calling looks like this:
public IActionResult Attendance(char accountType)
{
if (accountType.Equals("m") || accountType.Equals("a"))
{
return RedirectToAction("FacultyAttendance");
}
else
{
return RedirectToAction("StudentAttendance");
}
}
public IActionResult StudentAttendance()
{
// More functionality will be added later
return View();
}
public IActionResult FacultyAttendance()
{
// More functionality will be added later
return View();
}
Following this answer for calling the Controller method, I have this code snippet in the View file:
Attendance
This gives me the following error:
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid.
I also tried following this answer by removing the <%: and %>.
Attendance
If I do this, I just get blank webpage.
My first problem lies in which style I should use for this method call within the View file. Are either of these correct, or should I use something else entirely? Might the issue be with the way I have the Controller code set up?
Any help would be appreciated, as I am new to the MVC framework for ASP.NET.
Edit: The solution I found is a bit different than what I originally posted. I used this tag in my View and got it to work:
<a asp-controller="Home" asp-action="Attendance" asp-route-accountType='s'>Attendance</a>
I also followed ThisGuy's suggestions for improving the code since I had mismanaged some variables and that may have been part of the problem.
accountType is a char, but you are passing a string:
new {accountType = "m"}
Change the Controller to take a string instead of char for accountType.
public IActionResult Attendance(string accountType)
Also, I'd write it like this:
public IActionResult Attendance(string accountType) =>
RedirectToAction(
accountType.Equals("m") ||
accountType.Equals("a")
? nameof(FacultyAttendance)
: nameof(StudentAttendance));

How do I redirect to HTML page from within a controller?

Users receive an email with link that they must click on in order to certify their email address. Once the link is clicked, the user should be redirected to one of two static HTML pages, one saying "You're certified" the other stating "The link is expired"
I have attempted a few options. The first I added a Response.Redirect to my controller with a path to the View. I also tried where I added a routes.MapPageRoute to my RouteConfig file and changed my redirect call to attempt to use this name, but that doesn't work either. I looked at this example for that fix ( Redirect to an html page inside Views Folder )
Here is my code attempting to access the HTML file with the redirect:
EmailCertification.UpdateDBEmailCertified(userName, int.Parse(memberNumber), certSentDT);
return Redirect("~/Views/EmailCertification/EmailCertified.html");`
The error I get is that:
Path to /Views/EmailEmailCertification/EmailCertified.html is not found. I verified the spelling and the path is all is correct.
If I changed my code to include MapPageRoute in RoutesConfig it still doesn't work.
Here is my route config:
routes.MapPageRoute("HtmlPage", "EmailCertifiedURL", "~/Views/EmailCertification/EmailCertied.html");`
Here is my controller:
return Redirect("EmailCertifiedURL");
Here is my controller in action, it is a HttpPost
public ActionResult EmailCertify(string userName, string memberNumber, string certSentDate)
{
DateTime certSentDT;
long lngCertSent = long.Parse(certSentDate);
certSentDT = new DateTime(lngCertSent);
if (certSentDT < DateTime.Now.AddDays(-14))
return Redirect("EmailOldURL");
EmailCertification.UpdateDBEmailCertified(userName, int.Parse(memberNumber), certSentDT);
return Redirect("~/Views/EmailCertification/EmailCertified.html");
}
The error I get on this is that
the controller doesn't have a action EmailCertifiedURL. This code I took from the above mentioned StackFlow article.
All I want is the email link to fire off the controller action EmailCertify and redirect me to a static HTML page.
https://localhost:44344/EmailCertification/EmailCertify?userName=IS&memberNumber=3000050&certSentDate=636959314302036120
That seems strange. A work around could be adding a new action that returns your entire html with no layout. I mean, try with this
public ActionResult CertifiedEmail(){
return View();
}
Then you should create a view for your action with the same name ( CertifiedEmail.cshtml ), and inside your View paste all your html. At the beginning you should add this code to remove the Layout
#{
Layout = null;
}
I tend to use RedirectToAction() methods instead of just Redirect()
The 2nd parameter will need to be the name of the controller if it is a different controller.
return RedirectToAction("EmailCertifiedURL", "EmailCertification");
public ActionResult Questionnaire()
{
return Redirect("~/MedicalHistory.html");
}

asp mvc create seo friendly URL with parameter

I am trying to create seo friendly url.
current url:
http://www.example.com/Product/free-mobile-images/Mobile
expected ouput:
http://www.example.com/Product/free-mobile-images/
I am using id to fetch moblie data from database.
ActionMethod
public ActionResult Product(string seotext, string id)
{
return View();
}
Route.config
routes.MapRoute(
"Product",
"Product/{seotext}/{id}",
new { controller = "Home", action = "Product" });
I tried to remove moblie from the route value:
RouteData.Values.Remove("id");
RouteData.Values.Remove("Mobile");
But still I get /Mobile at the end of url.
May I know what wrong I am doing, any help would be great.
Why don't you just create a folder structure to mimic the path you want and then call your file Index.aspx, it will have the same effect but is much simpler.
Eg folder called Product, then inside that a folder called free-mobile-images and then your file called index.aspx

Retrieve URL for Action from Controller

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

ASP.NET MVC public alternative to UrlHelper.GenerateUrl

I want to embed a link to a controller action in my page so I can use it from javascript. Something like
var pollAction = '/Mycontroller/CheckStatus'
Now I am happy to hardcode it, but it would be really nice if there were a method I could use to create the URL. The AjaxHelper/HtmlExtensions contain methods to create hyperlinks (.ActionLink(...) and so on), but if you look into the guts of them, they rely on a method called UrlHelper.GenerateUrl() to resolve a controller and action into a url. This is internal so I can't really get at this.
Anyone found a good method in the framework to do this? Or must I roll my own?
Have you tried something along these lines?
var pollAction = '<%=Url.Action("CheckStatus", "MyController") %>';
If your page or control inherits from ViewPage or ViewUserControl, use the Url.Action method.
If not, use this instead:
String url = RouteTable.Routes.GetVirtualPath
(
((MvcHandler) HttpContext.Current.CurrentHandler).RequestContext,
new RouteValueDictionary
(
new
{
controller = "MyController",
action = "CheckState",
id = idParameter
}
)
).VirtualPath;
Place this inside a method on your code-behind and call it from the HTML view.

Categories