In ASP.NET MVC is there a way to enumerate the controllers through code and get their name?
example:
AccountController
HomeController
PersonController
would give me a list such as:
Account, Home, Person
Using Jon's suggestion of reflecting through the assembly, here is a snippet you may find useful:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
public class MvcHelper
{
private static List<Type> GetSubClasses<T>()
{
return Assembly.GetCallingAssembly().GetTypes().Where(
type => type.IsSubclassOf(typeof(T))).ToList();
}
public List<string> GetControllerNames()
{
List<string> controllerNames = new List<string>();
GetSubClasses<Controller>().ForEach(
type => controllerNames.Add(type.Name));
return controllerNames;
}
}
You can reflect through your assembly and find all classes which inherit from type System.Web.MVC.Controller. Here's some sample code that shows how you could do that:
http://mvcsitemap.codeplex.com/WorkItem/View.aspx?WorkItemId=1567
All who using this post better read this post before: using Assembly.GetCallingAssembly() not returns the calling assembly
The issue is that razor views are acting as independent dynamic assemblies and you don't get the desired assembly.
Yair
Create the property in every controller and then you get the name like this.
Related
I am doing an MVC 5 with API2 Controller Application.
I have a Controller that call an ApiController in the same project.
In my Api Controller Method I want to use DI.
It looks like this.
[ActionName("Method1")]
[HttpPost]
public int Method1(long User_id)
{
long user_id = Newtonsoft.Json.JsonConvert.DeserializeObject<long>(User_id.ToString());
IContactRepository _contactRepository = DependencyResolver.Current.GetService<IContactRepository>();
return _contactRepository.Get_CountMensajeByUser(user_id);
}
In order to use
[ActionName("RetProduct")] and [HttpPost]
I have to include using System.Web.Http; reference
But, in the other hand, in order to use DependencyResolver I have to include
using System.Web.Mvc;
when I include that reference, System.Web.Http; does not work.
Another alternative is to set de DI in the API Controller Constructor like this
private IContactRepository _sessionRepository;
public ApiController(IContactRepository contactRepository)
{
_contactRepository = contactRepository;
}
So i avoid to use DependencyResolver. But I have to use Parameters in the Controller Constructor.
On my controller where I call Api controller like this.
var webApi = new APIController();
model.CantMensajeByUser = webApi.CountMensajeByUser(10);
Where I am not using parameters.
What is the correct way to do it?
I think an easier solution for the problem you are trying to solve is to use an actual IoC container. For C#.NET in particular, Ninject is very easy to use and the best part is that you can resolve all of your dependencies in one file rather than doing that inside of your business logic.
I encourage you to check out http://www.ninject.org/.
I am trying to return 2 lists using nopCommerce, Both lists are read-only,
I am looking for the simplest way in doing this as I am writing a metro app and I don't really want to spend weeks learning MVC .
The first list is a list of categories from the base nopCommerce platform , the second list is a list of products.
Both lists need to be returned as JSON, to the calling client.
I have two questions:
Is there a way I can get this list without calling custom code ?
I wrote a plugin using the following code
using System.Collections;
using System.Collections.Generic;
using System.Web.Mvc;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Services.Catalog;
using Nop.Services.Customers;
using Nop.Core.Plugins;
namespace Nop.Plugin.Other.ONWWW.Controllers
{
public class ONWWWController : Controller
{
public ICategoryService _categoryService;
public ONWWWController(ICategoryService categoryService)
{
this._categoryService = categoryService;
}
public ActionResult Index()
{
return Json(_categoryService.GetAllCategories(), JsonRequestBehavior.AllowGet);
}
}
}
Why, when i run the code, I get the following error ?
No parameterless constructor defined for this object.
Question 1: Your best bet is the Nop.Plugin.Misc.WebServices plugin in the original source code.
Question 2: Did you see that the only constructor you have is
public ONWWWController(ICategoryService categoryService)
Which must accept a parameter? In other words, you have not registered the dependency properly. Try looking at one of the DependencyRegistrar.cs file in any of the default plugin. The Nop.Plugin.Misc.MailChimp plugin, for example, has a DependencyRegistrar.cs that you can refer.
:)
Hullo,
I am trying to update a website from ASP.NET MVC1 to ASP.NET MVC3 and from VS2008 to VS2010. So far everything seems to be going OK except the class FormCollection seems to be completely different across the two visual studios.
I've noticed that in VS2008 there is a FormCollection for version 1 and version 2 (presumably MVC1 and MVC2) and I can't see any big changes with them, but in VS2010 the only FormCollection class there is is a sealed class which is causing me grief as I have a class from before that inherits from FormCollection.
Anyone know if the FormCollection I used to know and love has moved or if I should just rewrite everything using the class that inherits it (a lot of stuff)?
Regards,
Harry
Worked my way around it now. Instead of inheriting FormCollection now it has it's own field 'form' which is a FormCollection instead and it's commands just act on that.
Edit:
People were asking for the codes, so here's the old class:
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using OpenProjects.Core;
namespace ProjectSupport.Web.Test
{
public class FormFor<TEntity> : FormCollection where TEntity : class
{
public FormFor<TEntity> Set<TReturn>(Expression<Func<TEntity, TReturn>> property, string value)
{
this[property.PropertyName()] = value;
return this;
}
}
}
And here's how it is now:
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using OpenProjects.Core;
namespace ProjectSupport.Web.Test
{
public class FormFor<TEntity> where TEntity : class
{
private FormCollection form;
public FormFor()
{
form = new FormCollection();
}
public FormFor<TEntity> Set<TResult>(Expression<Func<TEntity, TResult>> property, string value)
{
form.Add(property.PropertyName(), value);
return this;
}
public FormCollection ToForm()
{
return form;
}
}
}
For clarification on why this was being used rather than model binders, this was being used only for testing to easily mock up forms quickly and easily.
Newbie-ish questions ahead:
Where should I put my View Model declarations?
I created a file called "ViewModels.cs" in my Models folder.
I created a few View Model classes, including one called RatingViewModel:
using System;
using System.Collections.Generic;var
using System.Linq;
using System.Web;
namespace Web.Model
{
public class ViewModels
{
public class RatingViewModel
{
public User Rater { get; set; }
public Rating Rating { get; set; }
}
}
}V
Now I'm trying to create a helper/service class function that returns a new RatingViewModel object.
I created a "RatingsHelpers.cs" file.
But when I try to crate a new RatingViewModel object, it has no idea what I'm talking about.
I can't figure it out. Am I missing some reference? How can I create/return a new View Model object from my helper/service class?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Web.Model;
namespace System.Web.Mvc
{
public static class RatingsHelpers
{
public static RatingViewModel functionname()
{ ..... }
But it doesn't know what "RatingViewModel" is...!?!?!?
I just know this should be obvious.
Pulling my hair out,
Johnny
To sum up:
You've created a ViewModels class inside the Web.Model namespace. This class declares a nested class called RatingViewModel
Inside the helper RatingsHelpers located in the System.Web.Mvc namespace you are trying to access the RatingViewModel class.
You could achieve this by using ViewModels.RatingViewModel but I wouldn't recommend you doing so. Nesting classes like this makes no sense.
Instead you could place each view model class into a separate .cs file and put it directly into the Web.Model namespace:
namespace Web.Model
{
public class RatingViewModel
{
public User Rater { get; set; }
public Rating Rating { get; set; }
}
}
Then inside the helper class use could use directly the RatingViewModel class.
The problem is that you put the RatingViewModel class inside the ViewModels class, which means that it's a child class of ViewModels. I'm not sure that's the behaviour you want.
If you want to call a child class you have to write ViewModels.RatingViewModel to reference the class.
Expanding on what scripni said. Having a RatingViewModel class nested inside a ViewModels class inside the Web.Models seems superfluous. You probably want to get rid of the outer ViewModels class.
We're going through an ASP.Net MVC book and are having trouble with using an extenstion method within our view. The Extension method looks like this:
using System;
using System.Runtime.CompilerServices;
using System.Web.Mvc;
namespace MvcBookApplication
{
public static class HtmlHelperExtensions
{
public static string JQueryGenerator(this HtmlHelper htmlHelper, string formName, object model);
}
}
We use the extension method in our view like this:
<%=Html.JQueryGenerator("createmessage", ViewData.Model)%>
The problem is, that line of code says JQueryGenerator isn't a recognized method of HtmlHelper. I believe we've got the correct references set in the web project, but are there other things we can check? There's no using statement for views, is there?
Have you added a reference to MvcBookApplication namespace in your web.config ?