Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I want to know which is the best convention for controller, action and view naming in ASP.Net MVC
When i create a "Product" Controller, should i name it productController or ProductController ?
By default, visual studio Create ProductController.
But that means the url will be http://mywebsite/Product/xxxx
Or we should not have upper case like this in URLs ?
So i do not know which convention apply.
This is the same for view names and action names...
you can use First latter capital as default MVC does, and for lower case url you can use RouteCollection.LowercaseUrls Property
check below link
https://msdn.microsoft.com/en-us/library/system.web.routing.routecollection.lowercaseurls.aspx
Example:
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
}
Controller is just a class and should follow class capitalization rules, iow should use PascalCase: https://msdn.microsoft.com/en-us/library/x2dbyw72(v=vs.71).aspx
You can use StyleCop to check your code for such things as casing rules, spaces, etc: https://stylecop.codeplex.com/
But still nobody can prevent you from naming like 'productController'.
Also, if you wish to change appearance of controller name in URL, please check next question and corresponding answers (but usually people ten to use default naming): How to Change ASP.NET MVC Controller Name in URL?
In short, you can do this with RoutePrefixAttribute or by configuring routing (not shown here):
[RoutePrefix("product")]
public class ProductController
{
...
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Newbie question on ASP.Net MVC: I have a project and I manage two "Models" - let's say "Products" and "Clients". Each Model has it's own Controller, and set of Views to implement the basic CRUD operations.
Now I want to list from a different View (lets say Home Page) all Products and all Clients.
Should I create new methods in Products and Clients Controlers to list their items and call these methods from the Index view from Home? Should the Home Controller call the Products and Clients methods?
How should I correctly address this?
Thansk in advance!
Pedro
The answer to this question is to some degree both subjective and opinion-based. That being said..
It is fine for HomeController to call Product and Client related methods to return what will effectively become your HomeIndexViewModel (which would comprise of some kind of ProductViewModel and ClientViewModel properties - your view would access the data via Model.ProductViewModel, Model.ClientViewModel, etc).
I would go a step further and add an orchestration component, which will be responsible for handling the request and application logic required by the Index action of your HomeController. This should keep your controller thin and decoupled from the backend.
public class HomeController : Controller
{
private readonly IOrchestrator orchestrator;
public HomeController() : this(IOrchestrator orchestrator)
{
}
public HomeController(IOrchestrator orchestrator)
{
this.orchestrator = orchestrator;
}
public async Task<ActionResult> Index()
{
var homeIndexViewModel = await orchestrator.GetHomeProductsAndClientsAsync();
return View(homeIndexViewModel);
}
}
GetHomeProductsAndClientsAsync() will obviously be a method of your FooOrchestrator class that will be handling the application logic to return a HomeIndexViewModel.
The orchestrator is passed in to HomeController as an interface (IOrchestrator, rather than the FooOrchestrator class which will implement the IOrchestrator interface) to facilitate dependency injection (though, IMHO, the approach is still beneficial without DI).
Some reading:
"Never Mind the Controller, Here is the Orchestrator" (Dino Esposito)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I´m using asp.net core, and my controller name is "ConsultasController".
When pointing to localhost:5000\consultas an error says that there is no route for this.
So if I change to localhost:5000\consultum it works.
Why this is happening ?
Here are a few things to consider checking as without a breakdown of your routes and what your controller declarations look like, we would simply be guessing as to what could be the issue.
Check Your Default Routing
As long as you are using the default routes within your application, ASP.NET MVC should still use the name of your Controller to determine the route :
routes.MapRoute(
name: "default",
template: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" });
Do you have any other custom routes defined? Or is your default route pointing to the wrong location (i.e. Consultum instead of Consultas)?
Ensure Your Naming Is Correct
If you changed the name of your Controller, you'll want to ensure that you changed both the name of the class ConsultasController and the name of the file (ConsultasController.cs) and not just one or the other.
Any Route Attributes?
Additionally, do you have any specific route attributes defined for this Controller that could override the existing default routing? You'll want to ensure that your ConstultasController isn't pointing to ConsultumController :
[Route("Consultum")]
public class ConsultasController : Controller
{
/* Your code here */
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to order results based on a count of collection using Asp.net, web api2 and OData v4.
My url is: url/odata/groupeclients?$expand=Client&$orderby=Client/$count
I get this error :
"The query specified in the URI is not valid. The parent value for a
property access of a property '$count' is not a single value. Property
access can only be applied to a single value."
Is this supported in Web API OData? If not, is there any alternative solution?
Regards,
Hayfa
It's not currently supported; there's an open issue.
As a workaround, you could define an OData function bound to groupeclients that explicitly performs the expansion and ordering. Something like:
[HttpGet]
public IHttpActionResult OrderByClientCount()
{
return this.Ok(data.Include(e => e.Client).OrderBy(e => e.Client.Count));
}
Note that this code is untested and may not even be possible if your IQueryable data source does not support Include (or its equivalent).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am building an application where i do not want my user to fetch data off an on from the database. What i really want is to have all the relevant data to be fetched from the database inside a public array variable.
What I am currently doing is using a Public Shared variable. But I am unable to access that variable from other parts of my application.
Could somebody guide me on this requirement?
But I am unable to access that variable from other parts of my
application.
You need to create a Public Shared field or (better) property. You can use a class or Module (similar to a static class in C#):
Public Module MyGlobalVars
Public FooAs String = "Foo"
End Module
You can access it via class-name + field/property-name:
Dim foo As String = MyGlobalVars.Foo
You can also use a class which has the advanatage that you can use it's shrared constructor to load the array from database:
Public Class MyGlobalVars
Shared Sub New()
SomeDbStrings = GetDbStrings()
End Sub
Private Shared Function GetDbStrings() As String()
' load from db and return
End Function
Public Shared Property SomeDbStrings As String() = Nothing
End Class
The class or module must be accessible,
so if the class is in a different dll you need to reference it,
if it's in a different namespace you either have to specify the full path like
MyNamespace.MyGlobalVars.SomeDbStrings
or add the Imports statement at the beginning of the file.
Imports MyNamespace
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've been tasked with porting/refactoring a Web Application Platform that we have from ASP.NET to MVC.NET. Ideally I could use all the existing platform's configurations to determine the properties of the site that is presented.
Is it RESTful to keep a SiteConfiguration object which contains all of our various page configuration data in the System.Web.Caching.Cache? There are a lot of settings that need to be loaded when the user acceses our site so it's inefficient for each user to have to load the same settings every time they access.
Some data the SiteConfiguration object contains is as follows and it determines what Master Page / site configuration / style / UserControls are available to the client,
public string SiteTheme { get; set; }
public string Region { private get; set; }
public string DateFormat { get; set; }
public string NumberFormat { get; set; }
public int WrapperType { private get; set; }
public string LabelFileName { get; set; }
public LabelFile LabelFile { get; set; }
// the following two are the heavy ones
// PageConfiguration contains lots of configuration data for each panel on the page
public IList<PageConfiguration> Pages { get; set; }
// This contains all the configurations for the factsheets we produce
public List<ConfiguredFactsheet> ConfiguredFactsheets { get; set; }
I was thinking of having a URL structure like this:
www.MySite1.com/PageTemplate/UserControl/
the domain determines the SiteConfiguration object that is created, where MySite1.com is SiteId = 1, MySite2.com is SiteId = 2. (and in turn, style, configurations for various pages, etc.)
PageTemplate is the View that will be rendered and simply defines a layout for where I'm going to inject the UserControls
Can somebody please tell me if I'm completely missing the RESTful point here? I'd like to refactor the platform into MVC because it's better to work in but I want to do it right but with a minimum of reinventing-the-wheel because otherwise it won't get approval. Any suggestions otherwise?
Edit: Areas?" Would it be a viable option to use ASP.NET MVC 2 Areas, where each Area represents a different site, complete with css, javascript, etc.?
I agree with the accepted answer. Because this answer did not explicitly go into your question about being RESTful or not I would like to add something about that (1). And also go into your question about area's (2).
0. MVC.NET?
But first I want to say that for MVC.NET, the official term is ASP.NET MVC. With ASP.Net you probably meant ASP.NET Webforms. The full terms more clearly indicate MVC is still just an extension of ASP.NET. Then it's less of a surprise that you can also mix and match MVC views and 'old' .aspxpages in one and the same project, if you so choose. This CAN be an easy way to port a project from WebForms to MVC, by allowing stuff to migrated step-by-step over a periodand getting new stuff out there e.g. the Agile way. Note to be careful to update routing/URL's for users/SEO as you go).
1. Using cache
Using the cache for per-domain customization is indeed RESTful enough. I assume you mainly had question about 'stateless' property of true RESTful services. Only if you also did per-user customization with your SiteConfiguration object would you violate that. When config only differe changes per domain, the state/config is in-a-way encapsualted in the URL (e.g. the domain name) so the state/config travels to and from the user, and your service itself is stateless.
Also using .NET's Cache object as you propose instead of an alternative like the Application object has some advantage according to this SO article.
I personally dislike using the cache for basic acrchitectural things however, because it is untyped. So you have to cast all stuff from the cache. I'm nitpicking here because you have only one big configuration object, so this only has to be done once, and all the stuff in it is nicely typed. But still..
The site I've been working on lately also has per domain customization, but that is basically just the language the site is shown in. So directly at the beginning of each request (global.asax's Begin_Request) we simply set the current CultureID on the CurrentThread (this thread handles the incoming HTTP request for one domain, and serving the response). We can then show english for our-domain.com, French for our-domain.fr, etc. So the culture has a direct one to one mapping with the domain of the current URL. Localization logic can then be done using .resx files. We also have some limited conditional logic on this current cultureID spread throughout our code to allow having some parts being not available, or sending localized e-mails and other not directly request related stuff.
Long story, but spreading the per-domain specifics/config throughout your code in a similar way, based on current domain, would be an alternative. But this would not really reuse the existing logic as you say you wanted. SO I will mention one last alternative.,
You could use your existing SiteConfig class but then use a set of simple static variables (instances of the SiteConfiguration class) for each configuration type that you have. That way everything is neatly typed. You can map the domain name in the URL to the matching static configuration object at the beginning of each request as I indicated, and then access the config of the current request. That is assuming you have a managable number of sites, that are each quite distinct, and that and you don't have to be able to load configuration dynamically from a database or something. Note that using static variables they can still be loaded at app startup from either DB, or from web.config/appSettings (or something else). When you use web.config/appsettings it has the advantage that the site would automatically reload/restart with the new config when you change it.
2. Using Area's
About using area's for different sites instead of different domains. It depends on what you want. But I see area's more for allowing having different parts on one site, that are functionally different. E.g. that don't have much in common and therefore don't share any generic code. Area's basically allow you to put a group of somehow related controllers, models and views into one area of the site. And then via area routing, separate the different functionalities within one part of the site that is apparent to users also via starting with the same URL.
From what you say, it seems meer that all your sites share the same generic code, but are just customized through some configuration. So I don't think area's match your problem.
Setting this information in your cache is just fine but anytime your application recycles it will need to be reload which usually isn't a problem. I think this follows the model since each request is providing you with the info you need to pull from the cache since it is based on the requests domain and you don't really need to look it up in a DB or make a costly call to build it except for the first time.
You could also consider moving this data to your web.config file but I am assuming there is one site with many domains pointing to it that you want to customize?
Just make sure your indexing the cached data with the site it's associated with and accessing by that index because all domains pointing to one app will use only one cache.