c# mvc render a controller's action - by string name - c#

I'm having a hack around with the MVC framework, to try some proof of concept ideas. This are not production code..
Anyhow - I have an anonymous controller. I would like to execute an Action on that controller, however, I only have this controller's action name available as a string.
How can I render the controller's action via a string name?
Thank you all!
Franko

You have multiple options:
Asp.net MVC 2 Beta 2 (used to be part of MVC Futures) that has RenderAction() built in for these purposes
similar thing is implemented in MVC Contrib with Sub controllers
or you can have PartialRequest() as explained here
But you'll have to be careful since there are issues in all of them.
Even though. Your anonymous controller is probably going to be the main obstacle. But that depends on the way you have it and how you access it. It would be easier if you'd show us some code so we could provide some more insight into your problem.

Not sure about an anonymous controller?? But ...
If you have a look at the MVC futures project on codeplex they have a Html.RenderAction
Kindness,
Dan

Although I believe that your idea may not be optimal, you can use this code:
var controller = new SomeController(null);
var controllerContext = new ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current),new RouteData(),controller);
var actionInvoker = new ControllerActionInvoker();
actionInvoker.InvokeAction(controllerContext, "Test");
I you need more details about how this code works, look at System.Web.Mvc in Reflector.

Related

Is NancyFx reverse routing like ASP.NET MVC supported?

ASP.NET MVC allow very usable way of generating stongly typed URL like:
Business info
or even:
Business info
Using simple custom URL helper:
public static string Action<TController>(
this UrlHelper urlHelper,
Expression<Action<TController>> action,
string fragment = null
) where TController : BaseController
{
var routeValues = InternalExpressionHelper.GetRouteValuesFromExpression(action);
var url = UrlHelper.GenerateUrl(
routeName: null,
actionName: null,
controllerName: null,
protocol: null,
hostName: null,
fragment: fragment,
routeValues: routeValues,
routeCollection: urlHelper.RouteCollection,
requestContext: urlHelper.RequestContext,
includeImplicitMvcValues: true
);
return url;
}
It allows changing URL mapping in one place (RouteConfig) and any Controllers and Actions re-factoring doesn't mean you need to go and update each link.
I like NancyFx for it's simplicity and good IoC out of the box, but what i'm not sure why NanxyFx doesn't have support of reverse-routing (generating URL based on the action name) so it would be possible to create some static-typing helper for it.
Any ideas how to implement it in NancyFx or why if it's not possible to do, then why?
The accepted answer used to be right, but now there's Linker.
It doesn't do the expression parsing out of the box but it basically pulls parameters from property name-value pairs (like a RouteValueDictionary) so adding support for extracting the parameters from an expression tree shouldn't be too hard.
Routes are not named in Nancy so there's currently no way to implement such a feature.
But if you ever find yourself changing routes then I think you have a much bigger issue to begin with, personally this awesome feature (or lack of in your current case) has made me think more about what I'm making my routes, and so I now rarely, if ever, need to change my routes.
If I do need to rename a route, Find All makes it pretty quick to fix.

Is this possible to call the System.Web.HttpContext.Current.Request.Url in C# Models function?

I want the asp.net mvc domain in my C# code (model function). I trying to call this function on string but it's not worked.
string domain = "" + System.Web.HttpContext.Current.Request.Url;
When I tried to call same in controller's actionresult then this work but in c# models it's not work.
I hope the context will make it work but it's not worked.
Someone please explain me if something else I can use. What I want to do is getting url and I want to not pass the url (domain) form every call.
HttpContext.Current will only work if the code is executed within an existing HTTP context. For example this code will return null if you attempt to execute it in a unit test. It is a terribly bad practice to rely on any HttpContext specific things in your models. This property could be set in your controller (where you have access to the HttpContext) and then pass the model to your DAL and Service layers where the property will already be populated.
Depending on your context / models, it might not be available. This being said, you can pass the context in, or at least the url as a parameter to the model in need.

Is there a JSON-returning ASP.NET MVC for ajaxComboBox already?

The combobox in question http://plugins.jquery.com/project/ajaxComboBox
I forgot to note, I want to use it on ASP.NET MVC, i.e. sans the viewstates and the whole shebang
Why not just use the ajaxComboBox then? ASP.NET MVC doesn't have "viewstates and the whole shebang" as you put it, it's heavily reliant on you crafting the view (HTML) from the model that is presented through the controller (although you should optimially present something more like a modelview to the view, but that's off-topic).
First you would create a method on a controller which would return the items.
Then, in your view, you just have to write (in place) the url of the route to the method on your controller as the first parameter to ajaxComboBox and it should work.

ideas on building a strongly typed class to manage URLS for asp.net mvc

I want a strongly typed url class that i will reference whenever I need a url for any links, redirecting, etc.
I don't like:
RedirectToActoin("Action", "Controller");
A site with 50+ views means any naming change is going to break allot of things.
I also want a user frienly api so I can do:
MyUrls.ControllnerName.ActionName
How can I achieve this? is it possible?
Have a look at the T4MVC project (part of MvcContrib). It gives you strongly typed helpers for actions, controllers and views.
Excerpt from the project documentation:
T4MVC is a T4 template for ASP.NET MVC apps that creates strongly typed helpers that eliminate the use of literal strings when referring the controllers, actions and views. It helps make your MVC code much more maintainable, and gives you intellisense where you normally would not have any.
Instead of this:
<% Html.RenderPartial("DinnerForm"); %>
You can write this:
<% Html.RenderPartial(MVC.Dinners.Views.DinnerForm); %>
I actually prefer an approach inspired by the MVCContrib folks, which is to utilize a custom method on the controller that uses a Lambda Expression to specify where you are wanting to go.
protected internal RedirectToRouteResult RedirectToAction<TController>(Expression<Func<TController, object>> action) where TController: Controller
{
var controllerName = typeof(TController).Name.Replace("Controller", string.Empty);
var actionName = ((MethodCallExpression)action.Body).Method.Name;
return RedirectToAction(actionName, controllerName);
}
And using it would look like this:
return RedirectToAction<HomeController>(h => h.Index());
With this approach you get the advantages of having easy to read statements and when you refactor your action names these statements get updated as well (or cause build errors if you don't use the rename refactor).

Pros and cons for different lambda expression syntax in view helper call

I'm writing a view helper based on the ideas about partial requests from this blog post: http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/
In the controller action I prepare a widget by running:
AddWidget<Someontroller>(x => x.OtherActionName(new List<int>()));
Then in my view I can run the action and render the view output by doing some form of:
Html.RenderWidget...
And here comes my question, what compiler checked syntax would you choose from the following to use in the view:
Html.RenderWidget<SomeController, List<int>>(x => x.OtherActionName);
Html.RenderWidget<SomeController>(x => x.OtherActionName(null));
Html.RenderWidget<SomeController>(x => x.OtherActionName(It.IsAny<List<int>>);
Can anyone name some pros and cons? Or is it better to go with strings as the original Partial Request implementation does?
PS. Don't take the naming of It.IsAny> to litteraly, I just thought it was best described using the Moq naming.
Using the strings is significantly faster than using so-called strongly typed helpers (really; it's like 10 times faster), unless you implement some kind of caching for your Expression parsing. Note, though, that MVC 2 may have something along these lines RSN. So one option, if you can, is to just wait and see what's in the next preview drop. At the very least, you'll want to look like the rest of MVC, and the MVC team may end up doing your work for you.
("So called" because under the covers they're going to end up as strings in a RouteValueDictionary anyway.)

Categories