How to organize partial view in ASP.NET MVC3? - asp.net

I am trying to figure out how to organize my partial views in my project. Some people say to precede the name of a partial view with an _, but that makes for weirdly named actions in the controller if the view can be called directly.
Also, what should be done if the view can be a partial view in some cases and a regular view in other cases?
A common example for this is a search view that I embed on some pages to search for users in my app, but I also have a search page that loads the same view. I suppose I could create a second view for the search page that just embeds the partial view. Just wondering what other people are doing.

Honestly it's a matter of preference. You should do whatever works in your application with respect to avoiding code (or view) duplication etc.
The reason why we (I'm a dev on the team developing MVC) recommend preceding the partial view filename with an underscore is to more easily distinguish between full and partial views when looking at files in VS

I also use my partials with the underscore character as a prefix to easily distinguish between a view and a partial view when managing the files. As your project becomes bigger you may have a lot of files for a single controller, so this convention will help you a lot.
Besides, when you use a partial view you can call your views with an action using the following:
public ActionResult MyPartialAsAView()
{
// your code
return View("_myPartialView");
}
You have to remember that if you are using your partial as a View, you should assign the layout to it depending on the mode the partial is working (as a view or partial view), for example with a boolean property on your model class.

Related

MVC with Article Web Site

I am creating a Web site that will have a lot of articles. I created a ArticleController for the Web site. As an example, the first article to be implemented is Machine Language. So I created a view called machine_language.cshtml.
public class ArticleController : Controller
{
// GET: Article
public ActionResult Index()
{
return View();
}
public ActionResult Machine_Language()
{
return View();
}
}
So far in the controller I have to code above.
So my question is, I have 500 articles that need to be converted to start with. Normally, I created an ASPX page for each article, but now I am creating a view, since I am using MVC.
So does that mean I will need to have 500+ ActionResults in the ArticleController? One for each view/article.
Before I get started I want to make sure I'm doing this correctly, because it seems rather strange. If I have to create an action result with each article's name. I will end up having a huge ArticleController. Once there are a couple thousand articles, things will get seriously out of control.
Edit: P.S. I like to use pages for the articles. Since they are static content. I am trying to stay away from having huge articles with images, videos, etc... in a database.
How are you retrieving "article data/text"? In this particular situation, I'd have a View Model that has ArticleText as a property, and then you might need other article-specific items (tags? Author(s)? etc.).
Then pass this View Model from your controller's action to the view. The view would then be in charge of rendering this particular article to the user.
With this particular design, you'd have a single action in a single controller passing data (a single view model) to a single view.
In my opinion, that is the most scalable and the best approach.
Step away from the web forms thought where a single "viewing experience" equals on a "single entity" in the backend. That's the beauty and power (and scalability) of MVC.
I would recommend you that to render your existing aspx page to the view that you have using iframe. Since you have already static pages with you. And you can simply pass the page name as parameter for each article and you can achieve what you want. It's an alternative approach. Even if you want you can add images to those aspx pages and display the same here

Is it possible to "pipe" output from one view engine into another?

I was wondering if it is possible (even if it is a long shot) to pipe generated markup from one view engine into another with ASP.NET?
Could a view engine be built to explicitly to support such a thing (given the constraint of the ASP.NET Framework)?
What about Web Forms and Razor?
If you want to include output from one view (Razor) into the another could you create it as a partial view and call render partial in the other.
Even it your other view is not partial you can create some kind of "adapter partial view" that will call #Html.RenderAction() or #Html.RenderPartial() in order to include the first view.

ASP.NET MVC3 Partial View naming convention

I'm new to the MVC development so please bear with me. Is it really necessary to name my partial view like _Action.cshtml (with the _ underscore) to comply with the naming convention?
Here's my problem I have a controller (StudentController) and an action (List) that has a partial view file named "List.cshtml", and have
#{ Html.RenderAction("List", "Student"); }
to display this inside my HomeController - Index view as partial view which works. But if I name my partial view to _List.cshtml of course it will not work. Visual Studio could not even find the view for my action Student - List because it think it's still looking for the exact same name as my action (List.cshtml). What should I do?
I m so used to ASP.NET ascx with a pairing ascx.cs code. :(
It's not necessary to use an underscore, but it's a common convention for files which aren't meant to be served directly.
To solve this, you do have the option of returning a View or PartialView with the name of the view as a parameter.
return View("_List");
or
return PartialView("_List");
or inside another view
#{ Html.RenderPartial("_List"); }
If Partial view depends on ActionMethod and always render by Action method, you should same partial view name same as action method like this
public PartialViewResult List()
{
DoSomthing();
//PartialView() return a "List "Parial View
return PartialView();
}
but if your partial view not depends on the action method and directly call by view like this
#Html.RenderPartial("_List");
First, there is no shame to be new to any platform. And this was eight years ago so you are probably not new any more. You can use whatever naming conventions you want to use. I go with the original MVC naming convention which uses underscores (_) only for shared views. Partial views should be named after their actions. In your case the name of the view would be Action.cshtml unless this is a shared view of course.
My reasoning is simple. If you call View or PartialView from an action and don't provide a viewName, it assumes the name of the view is the name of the action. Also _Layout.cshtml is named with an underscore. This is because it is shared, not because it is a partial view. This mistake is all over the place in the MVC world. People are really zealously wrong about it. Don't know why. Naming convention is the shop's discretion.
The helper methods Html.RenderAction and Html.Action call actions on the controller. The helper methods Html.RenderPartial and Html.Partial allow you to pass a model directly to a Razor view without passing through an action.
One final thing, call Action instead of RenderAction. RenderAction is only called if you are already inside of a code block. This is almost never the case. I see people using RenderAction and then adding a code block around it unnecessarily just because the build breaks. These two following code snippets are exactly the same and the second one is way more readable in my opinion. I put the div to emphasize that the code is not in a code block:
<div>
#{ Html.RenderAction("List", "Student"); }
</div>
<div>
#Html.Action("List", "Student")
</div>
The bottom line is don't use underscores or curly braces unnecessarily. They are ugly characters and we should avoid them. ;)

Best placement for javascript in Asp.net MVC app that heavily uses partial views

What is the best place for javascript that is specific to a partial view? For example, if I have a partial view (loaded via ajax call) with some divs and I want to turn those divs into an accordian, would it be better put the $("#section").accordion() in script tags inside of the partial view, or in a .js file in the function that retrieves that partial view and inserts it into the DOM?
Obviously, common methods I will be keeping in a .js file, however I am more talking about javascript very specific to the partial view itself.
Most things I find on the net seem to say to put all javascript into a separate .js but nothing addresses the idea of partial views.
You can think of partial views as just more html in your web page, if that will help. The browser makes no distinction between html within the partial view, and the rest of the html surrounding it.
By that logic, the best place to put Javascript (including references to outside scripts) in a web page (whether it contains html that is part of a partial view or not) is in its canonical location at the bottom of the page, although there are exceptions.
If it will help the organization of your code, feel free to put the Javascript code that is specific to the partial view html in its own script file, and reference it in the web page at the bottom, with the rest of the script. Doing this will make no difference to the browser.

Using a Base Controller for obtaining Common ViewData

I am working on an ASP.NET MVC application that contains a header and menu on each page. The menu and header are dynamic. In other words, the menu items and header information are determined at runtime.
My initial thought is to build a base Controller from which all other controllers derive. In the base controller, I will obtain the menu and header data and insert the required information into the ViewData. Finally, I will use a ViewUserControl to display the header and menu through a master page template.
So, I'm trying to determine the best practice for building such functionality. Also, if this is the recommended approach, which method should I override (I'm guessing Execute) when obtaining the data for insertion into the ViewData.
I'm sure this is a common scenario, so any advice/best-practices would be appreciated! Thanks in advance!
EDIT:
I did find the following resources after posting this (of course), but any additional anecdotes would be awesome!
http://www.singingeels.com/Blogs/Nullable/2008/08/14/How_to_Handle_Side_Content_in_ASPNET_MVC.aspx
How do you use usercontrols in asp.net mvc that display an "island" of data?
Depends on where your information is coming from. We have standard view data that we use to generate some of the information we have on screen that we create in just this fashion. It works well and is easily maintained. We override the View method to implement strongly typed view names and use this information to retrieve some of the data that the master page requires as well.
You could write a helper extension to render the header/menu
That way you could have it show in different places in the view should you need to, but only one place for maintenance.
public static HtmlString MainMenu(this HtmlHelper helper)
Use a base controller class to implement generell filter methods. The controller class implements some filter interfaces IActionFilter, IAuthorizationFilter, IExceptionFilter and IResultFilter which are usefull to implement some common behavior for all controllers.
If the menu data is the same on all pages but different for each unique user.
Generate the menudata in an OnAuthorization or Initialize method of your controller base class. First will be called on authorization. Initialize will be called before every action method. You have access to ViewData Context. Generate the menudata there.
Put the view content for menu and header into the master page and access generated ViewData there.
I tackled a similar design challenge a couple months ago - implementing a breadcrumb feature that changes as user navigates from page to page.
I overrided the OnActionExecuting method to gather the breadcrumbs and store them in ViewData (I use the name of the action as the breadCrumb of the view). Then I updated the Master page to include a user control that takes the ViewData and renders the breadcrumbs.
One thing to be aware is that if you were using the default ASP.NET MVC error handling attribute [HandleError] and your error page is using the same Master page that attempts to read the ViewData, you will soon find out that you can't access ViewData from your error page and it will raise an exception. Depending on whether you need the ViewData for failure scenarios, the viable solution is to use a separate Master page or do this: How do I pass ViewData to a HandleError View?
I'll answer your question with another question. Will the base controller have to determine what type it really is in order to generate the proper menu data? If so, then you're defeating the purpose of polymorphism and the code to generate the data should go in each controller, perhaps in OnActionExecuting if the menu is the same for all actions. Pushing it back down into a parent class seems likely to end up with some switch statement in the parent class doing what each derived controller really ought to take care of.

Resources