.net mvc can I use razor within razor - c#

Nutshell:
How can I put an #Html.Action within and #Html.ActionLink ?
E.g using a default Visual Studio 2017 MVC project, there's a line in the _Layout.cshtml:
#Html.ActionLink("Application Name" , "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
But I want it to be:
#Html.ActionLink(#Html.Action("SiteName") , "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
where Action("SiteName") pulls in the .cshtml which is literally just a string with my site name in?!? Is this possible? Or can I maybe define a string via the Action somewhere at the start of my _Layout and put that in the ActionLink ?
History:
So I spent a while finding out how to have a global variable that I can call anywhere in my MVC View (My old question here which lead to this answer here
With the idea from the first answer, info from this site and with the noble aim of trying to stick to "the pattern" I've ended up creating
a ViewModel
public class SSVs
{
public string SiteName { get; }
}
and a PartialView
SiteName.cshtml
-This literally contains a string saying "My Site Name"
Now I'm introducing this dotted around my _Layout.cshtml using #Html.Action("SiteName")
It works! Great, and all I have to do to update every reference to my site name is change the SiteName.cshtml
Now I'm thinking sticking to "The pattern" was completely over the top and I need a much simpler way to hold some global variables...

Related

Generate Url to Razor Page in Area from Razor View

Within Razor View, I want to generate Url to specific Razor Page which is located in some Area.
I have already trying using this
#Url.Page("/Areas/Identity/Pages/Account/Manage/Orders", new { id = #Model.Id })
but what I get in return is
http://localhost:8888/Order/Submit/12345?page=%2FAreas%2FIdentity%2FPages%2FAccount%2FManage%2FOrders
while I would need this:
http://localhost:8888/Identity/Account/Manage/Orders?id=12345
Is it correct to assume that the only way to solve it is to apply customer routing? If yes, what would be the way? Thanks.
This should do the trick:
#Url.Page("/Account/Manage/Orders", new { id = Model.Id, area = "Identity"})

How to pass parameter to sitecore controller rendering method

I have this on my cshtml page
<div class="liveMatch-timer">
#Html.Sitecore().Controller("Blog", "LiveBlogHeader")
</div>
And this is my controller
public PartialViewResult LiveBlogHeader()
{
var matchHeader = GetMatchDayHeader();
return PartialView(BlogConstant.LiveBlogHeaderPath, matchHeader);
}
I have one hidden field with the name "liveMatchItemId" on my cshtml page. I would like to pass its value to controller so that I can access it inside controller. I am expecting to change controller definition something like this
public PartialViewResult LiveBlogHeader(string liveMatchItemId)
Anyone can help me understand on how can I do this? I am new to sitecore and MVC.
EDIT: I am able to achieve this using below code
#Html.Action("LiveBlogHeader", "Blog", new { liveMatchItemId = "12" })
But how can I set hidden field value instead of static field "12"?
Probably you could use something like:
#Html.Action("LiveBlogHeader", "Blog", new { liveMatchItemId = Model.LiveMatchItemId })
Where Model.LiveMatchItemId is the property that you want to pass to the controller.

How to set a default DateTime in field when new form is created?

I am very new to C# and MVC. I have a form with a number of fields and a created on field which I want to populate with the current date when the form is created.
I am using the Entity Framework approach rather than the code first approach. I am using Visual studio 2013 and version 5.2.3.0 of MVC.
I have tried a number of methods to get this working. e.g setting this with the Html.Editfor on the create page and also via validation attributes in the model itself. Here is what I have got so far...
Model...
Current Model to display validation attributes
Home Controller....
Home Controller
Create.cshtml...
#Html.EditorFor(model => model.allClientDetails.CreatedOn, "", new { #class = "text-danger" })
There seems to be many different ways to complete this task but I have not managed to get this working yet. Any help is greatly appreciated in advance.
The simplest way I can think of is, just send value from controller as part of model. Let say your model name is Student and you have a property called CreatedOn so your controller code should look like
Public ActionResult Index()
{
var student = new Student();
student.CreateOn = DateTime.Now;
return View(student);
}
In your view you
#Html.EditorFor(model => model.CreatedOn, new { #class = "text-danger" })
Hope it help :)
You can set defaults in the constructor:
public class Client_METADATA
{
public Client_METADATA()
{
CreatedOn = DateTime.Now;
}
}

Html.ActionLink to call an action from a different controller that's in a different folder

I've got a simple view that creates a link if a login is successful and is located under /Login:
<div>
#Html.ActionLink("Add a new Organization", "AddOrganization",
"/Setup/AddOrganizationController", new { id = Session["ID"] }, null)
</div>
After reading other similiar problems, I tried it adding the null after, as well as a few other overloads, but I can't get the link to work right. When I click the link, it takes me to
http://setup/AddOrganizationController/AddOrganization
Which is leaving out the localhost part that needs to be there. Without the null at the end, it tries to send me to
/Login/AddOrganization
All I want is a link that will run an action within the AddOrganizationController controller which is under /Setup directory. The link should also pass the session id to the controller as an argument. How can I do this?
If it's in the same Area then you can just do:
#Html.ActionLink("Add a new Organization", "AddOrganization", "Organizations", new { id = Session["ID"] })
where "Organizations" is the controller name.
Otherwise, if it's in another area you would do something like
#Html.ActionLink("Add a new Organization", "AddOrganization", "Organizations", new { area = "areaName", id = Session["ID"] }, null)

why a # character is added to the url?

I have a simple page displaying thumbnail list ,
I want to to add a pager , i have added two action links
<li class="ui-pagination-next">#Html.ActionLink("Next", "Paginate", "Home", new { nbSkip = ViewBag.nextSkip }, null)</li>
when i click on the link i'm redirected to
http://localhost:41626/#/Home/Paginate?nbSkip=60
instead of
http://localhost:41626/Home/Paginate?nbSkip=60 ,
does anyone know why the '#' character is added to the URL ?
Route copnfig :
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
by looking at your code i could find ui-pagination-next
this might mean that some other JS framework is actually listening to the click events of this link and doing some kind of ajax
hash "#" character is being used so that actually browser does not redirects to the page and at the same time maintains history
so if you press the browsers back button this additional peice of the link after # is removed and any JS framework subscribed to the evet knows how to handle it then
in simpler terms.
anything after the # in a url isnt sent to the server. Because some JS framework is handling the ajax part, it does not want that request should directly go to the server and also at the same time show look proper in the browsers address bar hence adds whatever you have in the link after the # and carries on with AJAX
heres an indepth article using hash for back and forward
From looking at your li class of ui-pagination-next im assuming jQuery Mobile is being used here.
jQuery Mobile by default, makes your links AJAX enabled
If you wish, you can prevent this by using:
$.mobile.ajaxLinksEnabled = false;
<script type="text/javascript">
$(function(){
$.mobile.ajaxLinksEnabled = false;
});
</script>
If i were you , I would use Ajax Raw ActionLink :
#Ajax.RawActionLink("NameofLink", "Action", "Controller", new { oid = 0, type = "oid and type are 2 parameters you want to send to action " }, new { id = "btnNewB", #class = "anyclass" })
Thank you all for your responses,
well seen #curt, in fact I'm using jQuery mobile, and what was causing the problem is mobile.changePage
Now I'm using simple button to navigate throw pages, but
$.mobile.ajaxLinksEnabled = false;
Does not resolve my problem with ajax link's. So I've done this, and it's working now
#Html.ActionLink("Previous", "Index", new { nbSkip = ViewBag.previousSkip }, new { data_role = "button", data_icon = "arrow-l", rel = "external", data_ajax = false })
Thanks #Parv Sharma for your explanation

Categories

Resources