Can we add Models in Layout.cshtml? - asp.net-mvc

i have layout of 4 pages and at header i need to access name of logged in admin. how to access that database model in admin in starting of layout i have added
#model ProjectName.Models.Admin
and while accessing name from admin i am writing
#Model.Name
it gives error how to do it in proper way to access that attribute in Layout and it cant be partial view it should be layout so kindly help

As #Stephen Muecke stated in his comment on your question, there are more ways how you can do that. I would recommend you to keep your Layout view without model. Otherwise as #Stephen Muecke mentions, you would have to make types of models for each view that uses that layout of either the same or derived type, which would add unnecessary complexity to your code.
So the other way is to call HtmlHelper.Action(...) or HtmlHelper.RenderAction() in your layout view at the place when you'd like to render user's name. Example:
Layout page:
...
<div class="admin-name">
#{ Html.RenderAction("AdminName", "Partial"); }
</div>
...
Add a controller:
public class PartialController : Controller {
[ChildActionOnly] // action cannot be requested directly via URL
public ActionResult AdminName() {
string adminName = ...; // assign value to adminName variable
return Content(adminName);
}
}

You need logged in user details in so many pages in application, so better to store logged in user details in Session and you can retrieve session value in any view/partial view.
Other Solution:
Make your header partial view and call from Layout
Html.RenderAction("actionName", "controllerName")

Create an action method in your controller which returns partial view
Controller Action Method
[HttpGet]
public ActionResult Header()
{
HeaderModel HM = new HeaderModel()
// Your user information in HeaderModel
return PartialView("Header", HM)
}
_layout.cshtml
<body>
<div>
#{Html.RenderAction("Header", "ControllerName");}
</div>
</body>
I hope this will resolve your problem.

Related

How to access a property of a model in _layout.cshtml

Well I am generating email templates using cshtml.
And I have one of the template like this.
#model Api.Model.SignUpViewModel
#{
Layout = "layout";
}
And in SignUpViewModel I have got a property isUnsubscribable
So in layout page I have to show a link for Unsubscribe based on this.
And I have few other Email Models which have this property, some others does't have this.
How can I send this data to Layout.cshtml
You want to create a parent ViewModel with your isUnsubscribable property. Then make your SignUpViewModel inherit from that parent.
Then in your layout page, your Model is as follows:
#model Api.Model.ViewModel
//Access your property here
And in your cshtml page, you will have the child viewmodel:
#model Api.Model.SignUpViewModel
This will work because both pages are getting what they need, when you pass the model in from the controller.
There is no need to send data to layout. It is already accessible there using below given syntax
#Model.isUnsubscribable

Determine security on shared layout

In my ASP MVC 3 website, I need a way to determine user security on a shared layout page. This layout page houses a navbar that needs to display drop down items based on a user's security level.
Originally I had thought I could make an Ajax call and populate a ViewBag item, then use that to determine what to show/not show. However, this won't work unless I want to put that same method in every controller/method.
Given this set up (navbar located on a shared layout), what is the best method for determining which items to show as the user navigates across different controllers/methods?
You could go two ways about this.
You could do a check in the View:
#if (User.Identity.IsAuthenticated){
// show logged in view
}
else{
// show logged out view
}
Or you could build a ViewModel and populate that from a shared action.
Example:
ViewModel
public class VM
{
public string Text{get; set;}
}
Shared Action on Shared Controller:
public class SharedController{
public PartialViewResult GetMenu(){
VM newvm = new VM(Text = "not logged in");
if (User.Identity.IsAuthenticated){
newvm.Text = "logged in";
}
return PartialView("Shared", newvm);
}
}
A partialview to render this action:
#Model VM
<p>
#model.Text
</p>
And lastly in your view:
#{
Html.RenderAction("Shared", "Shared");
}
You could implement your navbar as a PartialView which is returned by a ChildAction and inserted into the layout using a call to the ChildAction (#Html.Action(...)).
Within the ChildAction, you implement what to display or not depending on the logged in user (User.Identity).
The advantages are that there is only a single action which returns the navbar depending on the authenticated user, and you don't have to worry about any of this when working with your other controllers and their actions.

using update panel in ASP.NET MVC 4

Please explain me how to create update panel in ASP.NET MVC4 application. I looked for many blogs... but can not find any useful way.
This is my view
How I can separate these actions in same view?
Your two panels don't allow the user to switch between one or the other so I assume that you have an "intro" view with the option to either Sign in or Register. Right? In that case there is no real need for client side panel switching using Javascript/Ajax. Your "intro" view can pass a parameter to the controller action defining whether it needs a Sign In or Register view back.
For instance:
// RouteConfig.cs
routes.MapRoute(
name: null,
url: "login-register/{action}",
defaults: new { controller = "Authentication"},
constraints: new { action = #"(SignIn|Register)" }
);
// AuthenticationController.cs
public ActionResult SignIn()
{
...
return View(); // Will return the Authentication\SignIn.cshtml view
}
public ActionResult Register()
{
...
return View(); // Will return the Authentication\Register.cshtml view
}
Update panel does not really exist in ASP.NET MVC. It used to be there in ASP.NET Web form develeopment world before people actually realized it is better to use hand written jQuery ajax for doing the partial page update.
You may use jQuery ajax methods to post your form data to an action method and do partial page update to the page as needed. You may also consider using Partial view (to return a part of a page) as required.
In your case you can create 2 partial views for Sign in and Register and include those in your main view, to make your code more reusable.
<h1>Login or Register</h1>
<div>
#Html.Partial("Login")
</div>
<div>
#Html.Partial("Register")
</div>

ASP.NET MVC: Reuse of View by two controller actions

'Add' and 'Edit' views are typically more or less identical. How can I reuse a View so that Foos/Add and Foos/Edit/[Id] both use it? What would the actions look like?
Thanks
Simply specify the view name when calling the View() method like
public ViewResult Add() {
//...
return View("Foo");
}
public ViewResult Edit(int id) {
//...
var model = repository.get(id);
return View("Foo", model);
}
Your view will have to handle null/empty model values for the Add action or you could populate your model with default values.
You may want to consider using an Editor Template as opposed to reusing the same View. An Editor Template is a partial View that is used for editing and/or inserting data.
This would require separate views but the code would be minimal. The bulk of the code would be in the template which you would reuse for both the Add and Edit actions.
After you create your template, your Add View would look like (Razor):
#model Models.Foo
<h2>Add</h2>
<p>
#Html.EditorFor(model => model) // equivalent to EditorForModel()
</p>
And your Edit View would look like:
#model Models.Foo
<h2>Edit</h2>
<p>
#Html.EditorFor(model => model) // equivalent to EditorForModel()
</p>
I would use jQuery ajax. Clicking on Add or Edit would call serve action which will return the same PartialView (if you want to reuse it).
Then, in the success function of ajax call, you have just to put returned html (from that PartialView) into certain part of your page (or popup).
Nice and clean and no page reload...

ASP.NET MVC - Is partial view the right place to check if model is null or empty?

I have the following partial view:
#model IEnumerable<Foo>
<div id="foo">
#foreach (var foo in Model)
{
...
}
</div>
If collection is null or empty, I'd like to display some user friendly message, otherwise I'd like to list all collection items. Shell I make that check inside partial view, or inside calling method? What the best practice in this case and why?
Thank you!
Yes, the partial view is the right place - the reason to use a partial view is so your page only needs the view name and a reference to the collection. If you add the IsEmpty logic to the top level page you lose that encapsulation.
I'm not 100% familiar with Razor syntax, but I would create UI helper for that. To keep View simple I use following "rules": if I ever get if statement or a loop then I'll create UI helper.
I have static class for each context. Let's say I have a music store.. then I would have class called AlbumHelper
public static class AlbumHelper : {possible inheritance\
{
public static string CreateAlbumList(Model model)
{
// TODO: create list here using technique you prefer
// <ul><li>empty</li></ul>
return string.Empty;
}
}
That one I would call using (remember to add namespace to your Web.config):
<%= AlbumHelper.CreateAlbumList(Model) %>
If it would be commonly used control then I would create extension, so that it would be created using this line.
<%= Html.AlbumList(Model) %>
Here is a link to short tutorial for creating extension

Resources