Adding a View without a model MVC 5 - asp.net-mvc

I need to create a simple view with 3 links on it ( Administration type page ), I tried adding a View called index to a Directory called Administration but when I try to navigate to it it throws a resource not found error. I am brand new to MVC coming from Web Forms so sorry if this is a stupid question ;)

Firts Add a controller which will come with Index method. Right click on Index Method and select Add View.
Add all Html you want to add in that view and your page is ready without adding a Model.

You need to have a controller to render the view.
For instance, if you had an AdminController with a method similar to something like public ActionResult Index() { return View(); } this would render the index view where you could place your html/links etc.
The view itself doesn't need a model this way as you are not supplying anything when returning the View().
You could then navigate to the page by http://xxx/Admin/Index or, 'http://xxx/Admin/'.
It is well worth looking around SO and other various websites for MVC queries!
Good luck.

Related

Problems returning PartialViews from controller

I am using MVC 4 and I have some areas in my project and some Views and Partial Views within each area:
Areas
AdminArea => one area and so on
Views
Customer
Customer.cshtml => my View
_CustomerDetails.cshtml => my partial View
In my controller, CustomerController I have the following code that fails:
return PartialView("_CustomerDetails", model) => fails to find my partial view.
However, if I call
return PartialView("~/Areas/AdminArea/Views/Customer/_CustomerDetails.cshtml", model)
the code executes successfully.
My Views (not partial views) all work ok. I even have some some partial views (also in the same area) that render ok without specifying the full path, but for some reason, for the most of them the above code fails in constructor saying that:
The partial view '_CustomerDetails' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Customer/_CustomerDetails.cshtml a.s.o. ... => and is searching in global not in Admin area.
Is there any way to fix this problem without having to specify the full path to my PartialViews in code? (like passing area="Admin" like I do in the .cshtml file).
I am not using any custom ViewEngine and I have called AreaRegistration.RegisterAllAreas() in Global.asax.cs.
Thanks,
Tamash
I am really sorry for even posting this question:
The call from the controller worked fine, but the problem was that I was calling from javascript to get the PartialView through an action and I didn't specify the full name for that action. That's why the partial view wasn't returned since the method responsible for returning it wasn't being called at all.
Sorry about that: the code is a bit complex and I got lost in details around Ajax calls.
seems weird, try adding a view from controller action method i.e right click action method in controller, add view, make a view a partial view and see where it adds it.. check if it is the same location as you are putting, if not there is some structure prob/bug.

ASP.NET MVC partial view that updates without controller

I have a partial view that shows a list of Categories. I'd like to put that partial view on any page, but I'd like to have it to call to the service and get a list of categories by itself without me having to do that in every controller action. Something like webforms in which you can put a code-behind on it.
For eg.
Actions
public ActionResult Index()
{
JobListViewModel model = new JobListViewModel();
model.Categories= jobService.GetCategories();
return View(model);
}
public ActionResult Details(int id)
{
Job job = jobService.GetJob(id);
return View(job);
}
I created a partial that will take the model.Categories model and display a list. As you can see, the Index page will work fine, but I do not want to call it again in the Details page. Is there a way to make my partialview call to the GetCategories() service by itself?
Use Html.RenderAction - that gives the partial view its own controller action.
You should also mark you partial action with the attribute [ChildActionOnly].
DVark,
As noted in the accepted answer, for your scenario, RenderAction is the most appropriate.
I thought I'd link a little article that distils my thinking on the topic (i.e. when to use RenderPartial vs RenderAction):
http://cbertolasio.wordpress.com/2010/09/21/mvc-html-renderaction-vs-html-renderpartial/
hope it helps
[edit] - as an aside. a year or so ago, i got myself into a few scrapes by not appreciating the power of RenderAction, in favour of RenderPartial. as a result, i had littered the shared view space with lots of partialviews in order to access them from a variety of sources. the moral of the story: know your 'territory' before planting your flag.

Populating the model for a shared view, embedding a shared view within another view

I'm trying to embed a small view snippet that steps through a model fragment that works fine when I embed it in a single controller and pass it to a view like so;
Controller:
return View(_entities.formTemplate.ToList());
View:
http://www.pastie.org/666366
The thing is that I want to be able to embed this particular select box in more than just this single action / view, from the googling I've been doing this appears that it should go into a shared view, but I'm not clear then on how I could populate the model within that view from the controller? (or maybe I'm completely missing the purpose for shared views?)
In the other MVC framework I'm accustomed to working with there is the concept of a filter where you can call code before or after any action and mod the model as it passes the controller and goes to the view, is such a thing possible in .net mvc?
Any assistance appreciated.
You'll want to use the HtmlHelper method DropDownList() in order to create a input:
<%= Html.DropDownList("id", new SelectList(formBuilder, "ID", "Name")) %>
You probably want to use a ViewUserControl here.
You have a couple of options if you go that route. If it's model data that is easily available, recreate it at the call site of your RenderPartial like so:
<%=Html.RenderPartial("ViewName", new ModelData())%>
If it's data that is dependent on the current model data, then you'll need to pass that data somehow to your partial view.
ASP.Net MVC also has the concept of before/after controller actions. You decorate your controller method with an Attribute that derives from ActionFilterAttribute. In there, you have access to OnActionExecuting and OnActionExecuted.

Where to apply logic for a sidebar control in ASP.NET MVC

Take the example of wanting to have a "Latest news items" sidebar on every page of your ASP.NET MVC web site. I have a NewsItemController which is fine for pages dedicating their attention to NewsItems. What about having a news sidebar appear on the HomeController for the home page though? Or any other controller for that matter?
My first instinct is to put the logic for selecting top 5 NewsItems in a user control which is then called in the Master Page. That way every page gets a news sidebar without having to contaminate any of the other controllers with NewsItem logic. This then means putting logic in what I understood to be the presentation layer which would normally go in a Controller.
I can think of about half a dozen different ways to approach it but none of them seem 'right' in terms of separation of concerns and other related buzz-words.
I think you should consider putting it in your master page. Your controller can gather data (asynchronously, of course), store it in a nice ViewModel property for your view (or in TempData) and then you can call RenderPartial() in your master page to render the data.
The keeps everything "separate"
http://eduncan911.com/blog/html-renderaction-for-asp-net-mvc-1-0.aspx
This seems to address the question - even using the instance of a sidebar - but using a feature not included with MVC 1 by default.
http://blogs.intesoft.net/post/2009/02/renderaction-versus-renderpartial-aspnet-mvc.aspx
This also indicates the answer lies in RenderAction.
For anyone else interested, here's how I ended up doing it. Note you'll need to the MVC Futures assembly for RenderAction.
Basically you'd have something like this in your controller:
public class PostController
{
//...
public ActionResult SidebarBox()
{
// I use a repository pattern to get records
// Just replace it with whatever you use
return View(repoArticles.GetAllArticles().Take(5).ToList());
}
//...
}
Then create a partial view for SidebarBox with the content you want displayed, and in your Master Page (or wherever you want to display it) you'd use:
<% Html.RenderAction<PostController>(c => c.SidebarBox()); %>
Not so hard after all.
You can create a user control (.ascx) and then call RenderPartial().
Design a method in your controller with JsonResult as return type. Use it along with jQuery.
Use RenderAction() as suggested by elsewhere.
News section with ASP.NET MVC

Should I be calling each of my MVC views Index.aspx?

If I'm not mistaken - the conventions of ASP.NET MVC seem to want me to do the following for a controller view.
Thats to day I create 'Products' directory into which I place my 'Index' view. I then create a 'ProductsController' and create an 'Index' method on it which returns a View. Returning just View() with no arguments will go and fetch the 'Index.aspx' page because its the same name as the method.
public class ProductsController : Controller
{
public ActionResult Index()
{
return View(); // looks for Index.aspx in Products directory
}
}
Now thats just fine. BUT I'll end up with a billion Index.aspx pages, and I'm one of these people that never closes any files so I'll end up going crazy.
Alternatively I can create Products/Products.aspx and change my controller to the following :
public class ProductsController : Controller
{
public ActionResult Index() // my default routing goes to Index (from sample project)
{
return View("Products");
}
}
I understand how that works, and that its completely fine within the MVC design pattern to do this. Its not a hack or anything like that.
My problem (after listening to this PDC video) is that convention over customizabiltity is favored in MVC (or whatever the correct phrase is).
So I'm wondering if I'm missing a third way, or if people are just fine with 50 Index tabs in Visual Studio?
Having the default action for each controller have the same name just simplifies the routing (check global.asax). Also, it all things (Products, Books, Contacts, ...) use actions/views with the same name for the same function, then the code becomes much easier to navigate and understand. This use of convention is especially important when working as part of a team as it will encourage consistent code across developers.
While looking at another question, I ran across SimplyRestfulRouting in the MVCContrib project on codeplex. This might give you some ideas.
I think you should name the method after the action and name the view (if it makes sense and it's not shared between actions, the same as the action). You should probably change your routing mechanism as Index isn't really a descriptive name. The action name should represent what it does (just like any method) and shouldn't be hardcoded to Index or something like that. Routing should be edited instead.
It's just a pattern. Use the pattern, but make it work for you. Personally, I like to have my Views named by their function and I don't have many Index.aspx pages, because I don't have many indices.

Resources