Get Item in Sitecore MVC by its path - asp.net-mvc

I have created a Web rendering and try to get a specific Item by its path.
Something like this :
Item item=Sitecore.Context.Database.GetItem("/sitecore/content/home");
Is it possible to get item using #Model.Sitecore() ?
Thanks

I don't recommend it, but you can just get it in your view with #{ }
#{
var item = Sitecore.Context.Database.GetItem("/sitecore/content/home");
}
You should really move to a Sitecore controller rendering and do this work in the controller and return the Item as your model.
public class YourController : Controller
{
public ActionResult Stuff()
{
var item = Sitecore.Context.Database.GetItem("/sitecore/content/home");
return View(item);
}
}
Your view
#model Sitecore.Data.Items.Item
<div>
#Model.DisplayName
</div>

Related

Layout controller in mvc, uncertain about implemination

Hey guys I've got this function:
if (Cookies.CheckIfCookiesExists())
{
int.TryParse(Cookies.getWorkerCookieId("u-Site_Admin"), out uid);
var worker = unitOfWork.Workers.Get(uid);
ViewBag.isSuperAdmin = worker.IsSuperAdmin;
}
I want to pass the isSuperAdmin property down to the layout, and I need a controller to do this check every time the user switches between tabs.
My home controller returns this view:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "";
ViewBag.isSuperAdmin = ViewBag.isSuperAdmin;
}
Inside the layout what I care about is the Aside page:
#{ Html.RenderPartial("~/Views/Shared/partials/_aside.cshtml"); }
How would I go about achieving this? Basically the problem is the ViewBag value is lost like I've stated.
In the controller, set the ViewBag property.
Render the partial view within the view. Note that I'm using Html.Partial() instead of Html.RenderPartial.
The ViewBag property will be passed to the partial view.
Controller:
public class HomeController : Controller
{
public ActionResult Test()
{
ViewBag.isSuperAdmin = true;
return View();
}
}
View:
#{
ViewBag.Title = "Test";
}
<h2>Test</h2>
#Html.Partial("~/Views/Shared/partials/_aside.cshtml")
Partial View:
<h3>ViewBag.isSuperAdmin = #ViewBag.isSuperAdmin</h3>
Result:

Pass list of categories to partial view

I have a partial view which will display list of Main Categories and under each Main Category all of its subcategories. But the problem is I don't know how can I pass this Category List to my partial view. Please check the code bellow. I've also attached my .edmx table map picture to give you better idea. Once I pass it to partial view I want to loop though all categories and sub categories to display them
[ChildActionOnly]
public PartialViewResult _GuestNav()
{
using (var db = new TestEntities())
{
db.Categories.ToList(); // get list from here
return PartialView("_GuestNav"); // then pass that list to partial view
}
}
Here is the main action code:
public ActionResult Categories()
{
using (var dbCtx = new DbContext())
{
var categories = dbCtx.Categories.Include(x => x.SubCategories).ToList()
return View(categories);
}
}
Then in your Categories.cshtml you will have the code as below:
#model IEnumerable<Categories>
<ul>
#foreach(var category in Model)
{
<li>#category.CategoryName
#if(category.SubCategories.Any())
{
Html.RenderPartial("~/Partial/_SubCategory.cshtml", category.SubCategories);
}
</li>
}
</ul>
At last you supply a partial view called _SubCategory.cshtml in the Partial folder of Category folder as below:
#model IEnumerable<SubCategory>
<ul>
#foreach(var subCategory in Model)
{
<li>#subCategory.SubCategoryName</li>
}
</ul>
In your case if you want to pass this list to the partial view you specified you can do it as below:
[ChildActionOnly]
public PartialViewResult _GuestNav()
{
using (var db = new TestEntities())
{
var categories = db.Categories.Include(x => x.SubCategories).ToList(); // Added the include if you want to add subcategories as well
return PartialView("_GuestNav", categories); // then pass that list to partial view
}
}
Yo can use model binding, pass a Model or ViewModel as a parameter and access it from the partial view. For example, in your _GuestNav action:
...
return PartialView("_GuestNav",db.Categories.ToList());
Here's a link on how to accomplish that.
Then you can bind the model in your view. For example:
...
#model IEnumerable<Categories>;
For more detail, check out the examples from the link.
The PartialView method has an override that accepts an object. You need to store the results of the db.Categories.ToList() call in a variable and pass that to the method like this:
using (var db = new TestEntities())
{
var cats = db.Categories.Include("SubCategories").ToList(); // get list from here
return PartialView("_GuestNav", cats); // then pass that list to partial view
}
Just make sure your partial view expects a list of categories as its model. Then, inside your view you can iterate over the model and display the subcategories.
You should also look into how to use a viewmodel for your views.
EDIT
You may need to use an include statement since navigation properties are generally lazy loaded. Updated my answer.

Passing Data to View

I'm new to MVC and trying to pass data from a view to page and am having two problems:
The ID that is in the page url is not being passed to the controller
(customers/details/1)
I cannot get the variable to be written to the page. (i've been told
to try avoiding the use of viewbag and viewdata).
My controller looks like this:
public class CustomersController : Controller
{
public ActionResult Details(int? pageIndex)
{
var Name = "Nope";
if(pageIndex == 1)
{
Name = "John Smith";
};
return View(Name);
}
}
}
My view look like this:
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Details</h2>
<p>#Model.Name</p>

MVC5 HTML ActionLink Throws CS1502

I've created a very simple view class in my MVC5 solution. It uses the Entity Framework and calls one of the controller class's actions. I want to output a list of VIN numbers as hyperlinks on my home page.
The view class syntax is as follows:
#{
ViewBag.Title = "Vehicle Inventory";
}
#model IEnumerable<TavernaMVC.Controllers.InventoryController>
<ul>
#foreach (var item in Model)
{
<li>#item</li>
}
</ul>
The error is as follows:
CS1502: The best overloaded method match for
'System.Tuple.Create<object,int>(object, int)' has some invalid arguments
How do I rectify my code so that each VIN's details are output in the view class? Alternatively, how would I simply output all the VIN values as hyperlinks?
First, you should not use your controller as model. What model class are you using? Since you're talking about VIN I will guess it can be called Car:
public class Car {
public int VIN { get; set; }
public string Details { get; set; }
}
In your controller you would then like to do something like:
public ActionResult Index() {
var cars = db.Cars.ToList();
return View(cars);
}
Then, define your view as:
#model IEnumerable<TavernaMVC.Models.Car>
#{
ViewBag.Title = "Vehicle Inventory";
}
<ul>
#foreach (var item in Model)
{
<li>#item.VIN</li>
}
</ul>
Your view looks correct if the TavernaMVC.Controllers.InventoryController class looks somewhat like:
public class TavernaMVC.Controllers.InventoryController
{
//VIN
public string VIN{get;set;}
//Url to Details
public URL Details{get;set;}
}
and you use this
<li>#item.VIN</li>
as the li line
Check for renamed Properties in the first line ...
I had this error after renaming a Property and using the AutoRefactoring in the Visual Studio which does not change the Properties in CSHTM files.

Passing Data From View back to the HttpPost method in MVC

Alright so i want to pass data from the view back to Post Method in the controller.
The View :
#model IEnumerable< MvcMobile.Models.Trips>
<p>Time : #ViewBag.titi</p>
<p>ID :#ViewBag.iid </p>
<p>From : #ViewBag.From</p>
<p>To :#ViewBag.To </p>
Avaibliabe Trips :
#foreach (var item in Model)
{
if ( item.Time==ViewBag.titi)
{
<p>#item.TripID</p>
}
}
My HttpGet Method in the controller :
[HttpGet]
public ActionResult Book2(MvcMobile.Models.TicketsBooked tik)
{
ViewBag.titi = tik.Time;
ViewBag.iid = tik.TicketID;
ViewBag.from = tik.From;
ViewBag.To = tik.To;
var TripsList = db.Trips.ToList();
return View(TripsList);
}
In This case i cant use a dynamic object to pass variable since the model is IEnumerable
i want to pass one or two textBoxes back to the controller, how can i do that ?
an alternative question would be how can i do the same functionality in the view without making the model IEnumberable ?
and thanks alot.
You should read up on using view models. Basically it's best practice to only pass relevant data to the view. So instead on passing a model of IEnumerable you would have a view model with a property of IEnumerable plus the extra properties you want to post back to your controller.
So for example:
public class ViewModel
{
public IEnumerable<MvcMobile.Models.Trips> Trips { get; set; }
public string ExtraValue { get; set; }
}
and your view would be:
#foreach(var trip in Model.Trips)
{
<p>Do stuff</p>
}
#Html.TextBoxFor(m => m.ExtraValue)
Your post method would then accept a ViewModel.
[HttpPost]
public ActionResult Book2(ViewModel viewModel)
{
}
You can read up more on view models here or by searching Google / SO. There are many, many examples.

Resources