Search Results

Search found 39 results on 2 pages for 'urlhelper'.

Page 1/2 | 1 2  | Next Page >

  • Unit testing ASP.NET Web API controllers that rely on the UrlHelper

    - by cibrax
    UrlHelper is the class you can use in ASP.NET Web API to automatically infer links from the routing table without hardcoding anything. For example, the following code uses the helper to infer the location url for a new resource,public HttpResponseMessage Post(User model) { var response = Request.CreateResponse(HttpStatusCode.Created, user); var link = Url.Link("DefaultApi", new { id = id, controller = "Users" }); response.Headers.Location = new Uri(link); return response; } That code uses a previously defined route “DefaultApi”, which you might configure in the HttpConfiguration object (This is the route generated by default when you create a new Web API project). The problem with UrlHelper is that it requires from some initialization code before you can invoking it from a unit test (for testing the Post method in this example). If you don’t initialize the HttpConfiguration and Request instances associated to the controller from the unit test, it will fail miserably. After digging into the ASP.NET Web API source code a little bit, I could figure out what the requirements for using the UrlHelper are. It relies on the routing table configuration, and a few properties you need to add to the HttpRequestMessage. The following code illustrates what’s needed,var controller = new UserController(); controller.Configuration = new HttpConfiguration(); var route = controller.Configuration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "id", "1" }, { "controller", "Users" } } ); controller.Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:9091/"); controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, controller.Configuration); controller.Request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);  The HttpRouteData instance should be initialized with the route values you will use in the controller method (“id” and “controller” in this example). Once you have correctly setup all those properties, you shouldn’t have any problem to use the UrlHelper. There is no need to mock anything else. Enjoy!!.

    Read the article

  • Unit Testing UrlHelper Extension Methods

    - by fregas
    I'm trying to create unit tests to make sure my extension methods for UrlHelper work? Does anyone know how to do this? I'm using MVC 1.0 and MvcContrib. I can test the routes but can't test code like this: public static string MoreFloorplans(this UrlHelper urlHelper, long productID, int pageIndex) { return urlHelper.Action<CatalogController>(x => x.GetRelatedProducts(productID, pageIndex)); }

    Read the article

  • How to inject UrlHelper in MVC using Castle Windsor

    - by zaph0d
    I have a component that has a dependency on UrlHelper that I need to register using Castle Windsor. UrlHelper in turn has depdendencies on RequestContext (and RouteCollection). Now my controller has a Url property of type UrlHelper but cannot really access this as far as I can tell. What is the most efficient way to register my UrlHelper dependency (using fluent configuration)?

    Read the article

  • can't access to an extension method with UrlHelper parameter in controller! Vice versa in view have

    - by Sadegh
    why defined extension method with UrlHelper don't added in Url.EXTENSIONMETHOD when i want to use it in controller! but i have access to it in view? public static string Home(this UrlHelper helper) { return helper.RouteUrl("ABC", new { controller = "ABC", Action = "Default" }); } i haven't access: public ActionResult Default() { return Redirect(Url.Home()); } i have access in view: <a href="<%=Url.Home() %>" title="Hello">Hello</a>

    Read the article

  • Unittesting Url.Action (using Rhino Mocks?)

    - by Kristoffer Ahl
    I'm trying to write a test for an UrlHelper extensionmethod that is used like this: Url.Action<TestController>(x => x.TestAction()); However, I can't seem set it up correctly so that I can create a new UrlHelper and then assert that the returned url was the expected one. This is what I've got but I'm open to anything that does not involve mocking as well. ;O) [Test] public void Should_return_Test_slash_TestAction() { // Arrange RouteTable.Routes.Add("TestRoute", new Route("{controller}/{action}", new MvcRouteHandler())); var mocks = new MockRepository(); var context = mocks.FakeHttpContext(); // the extension from hanselman var helper = new UrlHelper(new RequestContext(context, new RouteData()), RouteTable.Routes); // Act var result = helper.Action<TestController>(x => x.TestAction()); // Assert Assert.That(result, Is.EqualTo("Test/TestAction")); } I tried changing it to urlHelper.Action("Test", "TestAction") but it will fail anyway so I know it is not my extensionmethod that is not working. NUnit returns: NUnit.Framework.AssertionException: Expected string length 15 but was 0. Strings differ at index 0. Expected: "Test/TestAction" But was: <string.Empty> I have verified that the route is registered and working and I am using Hanselmans extension for creating a fake HttpContext. Here's what my UrlHelper extentionmethod look like: public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, object>> actionExpression) where TController : Controller { var controllerName = typeof(TController).GetControllerName(); var actionName = actionExpression.GetActionName(); return urlHelper.Action(actionName, controllerName); } public static string GetControllerName(this Type controllerType) { return controllerType.Name.Replace("Controller", string.Empty); } public static string GetActionName(this LambdaExpression actionExpression) { return ((MethodCallExpression)actionExpression.Body).Method.Name; } Any ideas on what I am missing to get it working??? / Kristoffer

    Read the article

  • How do I test UrlHelper.RouteUrl()?

    - by Jeff Putz
    I'm having a tough go trying to figure out what I need to mock in my tests to show that UrlHelper.RouteUrl() is returning the right URL. It works, but I'd like to have the right test coverage. The meat of the controller method looks like this: var urlHelper = new UrlHelper(ControllerContext.RequestContext); return Json(new BasicJsonMessage { Result = true, Redirect = urlHelper.RouteUrl(new { controller = "TheController", action = "TheAction", id = somerecordnumber }) }); Testing the result object is easy enough, like this: var controller = new MyController(); var result = controller.DoTheNewHotness()); Assert.IsInstanceOf<JsonResult>(result); var data = (BasicJsonMessage)result.Data; Assert.IsTrue(data.Result); result.Redirect is always null because the controller obviously doesn't know anything about the routing. What do I have to do to the controller to let it know? As I said, I know it works when I exercise the production code, but I'd like some testing assurance. Thanks for your help!

    Read the article

  • ASP.NET MVC: How to create a usable UrlHelper instance?

    - by Marek
    I am using quartz.net to schedule regular events within asp.net mvc application. The scheduled job should call a service layer script that requires a UrlHelper instance (for creating Urls based on correct routes (via urlHelper.Action(..)) contained in emails that will be sent by the service). I do not want to hardcode the links into the emails - they should be resolved using the urlhelper. The job: public class EvaluateRequestsJob : Quartz.IJob { public void Execute(JobExecutionContext context) { // where to get a usable urlHelper instance? ServiceFactory.GetRequestService(urlHelper).RunEvaluation(); } } Please note that this is not run within the MVC pipeline. There is no current request being served, the code is run by the Quartz scheduler at defined times. How do I get a UrlHelper instance usable on the indicated place? If it is not possible to construct a UrlHelper, the other option I see is to make the job "self-call" a controller action by doing a HTTP request - while executing the action I will of course have a UrlHelper instance available - but this seems a little bit hacky to me.

    Read the article

  • UrlHelper and ViewContext inside an Authorization Attribute

    - by DM
    I have a scenario that I haven't been able to solve: I'm toying around with creating my own custom authorization attribute for mvc. The main bit of functionality I would like to add is to have the ability to change where the user gets redirected if they are not in a certain role. I don't mind that the system sends them back to the login page if they're not authenticated, but I would like to choose where to send them if they are authenticated but not allowed to access that action method. Here's is what I would like to do: public class CustomAuthorizeAttribute : AuthorizeAttribute { public string Action; public string Controller; protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { // if User is authenticated but not in the correct role string url = Url.Action(this.Action, this.Controller); httpContext.Response.Redirect(url); } } And as an added bonus I would like to have access to ViewContext and TempData before I do the redirect. Any thoughts on how I could get instantiate a UrlHelper and ViewContext in the attribute?

    Read the article

  • Rearranging parts of the URL result from link_to in Rails

    - by mathee
    This is how I'm doing it now: link_to "Profile", :controller => "profiles", :action => "asked", :id => @profile # => <a href="/profiles/asked/1">Profile</a> Does it make more sense for the URL to be <a href="/profiles/1/asked">Profile</a>? Profile 1 asked some number of questions, so it makes more sense to me for the URL to look like: /:controller/:id/:action. If you agree, how do I accomplish this? If you don't agree, please let me know why. (I'm new to Ruby on Rails, so I'm still getting used to MVC conventions.) Any advice would be great!

    Read the article

  • How to use Code Igniter to show Dynamic images via javascript(jQuery).

    - by aaroninfidel
    You can use the URL helper in Code Igniter to load CSS and Javascript with the base_url() method, but what if you have images dynamically being placed into your HTML via javascript? for example in my javascript file I've got var arrowimages={down:['downarrowclass', 'images/down.png', 23], right:['rightarrowclass', 'images/right.png']} and those images will be placed into whatever menu item I've specified has a drop down menu. but that file is a .js file so obviously the server won't load php inside of it. so, how can I set the base url for the JS? Thanks! -Aaron

    Read the article

  • what is the right 'rails' way to add a link_to a new custom method

    - by jpwynn
    We're adding a new method 'delete_stuff' to the WidgetsController of a scaffolded app. in routes we added match 'widget/delete_stuff/:id' = 'widgets#delete_stuff' I CAN manually create html (GET) links like <a href="/widget/delete_stuff/<% widget.id %>">My Custom Delete Stuff</a> But that's bad on so many levels (uses GET instead of DELETE, doesn't permit a CONFIRM dialog, isnt DRY, etc) Problem is I can't figure out how to use the url helpers for a custom method... trying to do something like this: <% link_to 'DeleteStuff', @widget, :confirm => 'Are you sure?', :method => :delete %> But that just gets ignored when the html is rendered. I'm clearly missing something fundamental on how to use link_to, any help will be appreciated! Cheers, JP

    Read the article

  • Handy ASP.NET MVC 2 Extension Methods &ndash; Where am I?

    - by Bobby Diaz
    Have you ever needed to detect what part of the application is currently being viewed?  This might be a bigger issue if you write a lot of shared/partial views or custom display or editor templates.  Another scenario, which is the one I encountered when I first started down this path, is when you have some type of menu and you’d like to be able to determine which item represents the current page so you can highlight it in some way.  A simple example is the menu that is created as part of the default ASP.NET MVC 2 Application template.   <div id="menucontainer">       <ul id="menu">         <li><%= Html.ActionLink("Home", "Index", "Home") %></li>         <li><%= Html.ActionLink("About", "About", "Home") %></li>     </ul>   </div>   The part that got me at first, however, was the following entry in the default style sheet (Site.css):   ul#menu li.selected a {     background-color: #fff;     color: #000; }   I assumed that the .selected class would automatically get applied to the active menu item.  After trying a few different things, including the MvcContrib MenuBuilder, I decided to write my own extension methods so I would have more control over the output.  First, I needed a way to determine what view the user has navigated to based on the requested URL and route configuration.  Now, I am sure there are many ways to do this, but this is what I came up with:   public static class RequestExtensions {     public static bool IsCurrentRoute(this RequestContext context, String areaName,         String controllerName, params String[] actionNames)     {         var routeData = context.RouteData;         var routeArea = routeData.DataTokens["area"] as String;         var current = false;           if ( ((String.IsNullOrEmpty(routeArea) && String.IsNullOrEmpty(areaName)) ||               (routeArea == areaName)) &&              ((String.IsNullOrEmpty(controllerName)) ||               (routeData.GetRequiredString("controller") == controllerName)) &&              ((actionNames == null) ||                actionNames.Contains(routeData.GetRequiredString("action"))) )         {             current = true;         }           return current;     }       // additional overloads omitted... }   With that in place, I was able to write several UrlHelper methods that check if the supplied values map to the current view.   public static class UrlExtensions {     public static bool IsCurrent(this UrlHelper urlHelper, String areaName,         String controllerName, params String[] actionNames)     {         return urlHelper.RequestContext.IsCurrentRoute(areaName, controllerName, actionNames);     }       public static string Selected(this UrlHelper urlHelper, String areaName,         String controllerName, params String[] actionNames)     {         return urlHelper.IsCurrent(areaName, controllerName, actionNames)             ? "selected" : String.Empty;     }       // additional overloads omitted... }   Now I can re-work the original menu to utilize these new methods.  Note: be sure to import the proper namespace so the extension methods become available inside your views!   <div id="menucontainer">       <ul id="menu">         <li class="<%= Url.Selected(null, "Home", "Index") %>">             <%= Html.ActionLink("Home", "Index", "Home")%></li>           <li class="<%= Url.Selected(null, "Home", "About") %>">             <%= Html.ActionLink("About", "About", "Home")%></li>     </ul>   </div>   If we take it one step further, we can clean up the markup even more.  Check out the Html.ActionMenuItem() extension method and the refined menu:   public static class HtmlExtensions {     public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, String linkText,         String actionName, String controllerName)     {         var html = new StringBuilder("<li");           if ( htmlHelper.ViewContext.RequestContext                 .IsCurrentRoute(null, controllerName, actionName) )         {             html.Append(" class=\"selected\"");         }           html.Append(">")             .Append(htmlHelper.ActionLink(linkText, actionName, controllerName))             .Append("</li>");           return MvcHtmlString.Create(html.ToString());     }       // additional overloads omitted... }   <div id="menucontainer">       <ul id="menu">         <%= Html.ActionMenuItem("Home", "Index", "Home") %>         <%= Html.ActionMenuItem("About", "About", "Home") %>     </ul>   </div>   Which generates the following HTML:   <div id="menucontainer">       <ul id="menu">         <li class="selected"><a href="/">Home</a></li>         <li><a href="/Home/About">About</a></li>     </ul>   </div>     I have created a codepaste of these extension methods if you are interested in using them in your own projects.  Enjoy!

    Read the article

  • Resolve a URL from a Partial View (ASP.NET MVC)

    Working on an ASP.NET MVC application and needed the ability to resolve a URL from a partial view. For example, I have an image I want to display, but I need to resolve the virtual path (say, ~/Content/Images/New.png) into a relative path that the browser can use, such as ../../Content/Images/New.png or /MyAppName/Content/Images/New.png. Astandard view derives from the System.Web.UI.Page class, meaning you have access to the ResolveUrl and ResolveClientUrl methods. Consequently, you can write markup/code like the following:' /The problem is that the above code does not work as expected in a partial view. What's a little confusing is that while the above code compiles and the page, when visited through a browser, renders, the call to Page.ResolveClientUrl returns precisely what you pass in, ~/Content/Images/New.png, in this instance. The browser doesn't know what to do with ~, it presumes it's part of the URL, so it sends the request to the server for the image with the ~ in the URL, which results in a broken image.I did a bit of searching online and found this handy tip from Stephen Walther - Using ResolveUrl in an HTML Helper. In a nutshell, Stephen shows how to create an extension method for the HtmlHelper class that uses the UrlHelper class to resolve a URL. Specifically, Stephen shows how to add an Image extension method to HtmlHelper. I incorporated Stephen's code into my codebase and also created a more generic extension method, which I named ResolveUrl.public static MvcHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url) { var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); return MvcHtmlString.Create(urlHelper.Content(url)); }With this method in place you can resolve a URL in a partial view like so:' /Or you could use Stephen's Html.Image extension method (althoughmy more generic Html.ResolveUrl method could be used in non-image related scenarios where you needed to get a relative URL from a virtual one in a partial view). Thanks for the helpful tip, Stephen!Happy Programming!Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Resolve a URL from a Partial View (ASP.NET MVC)

    Working on an ASP.NET MVC application and needed the ability to resolve a URL from a partial view. For example, I have an image I want to display, but I need to resolve the virtual path (say, ~/Content/Images/New.png) into a relative path that the browser can use, such as ../../Content/Images/New.png or /MyAppName/Content/Images/New.png. Astandard view derives from the System.Web.UI.Page class, meaning you have access to the ResolveUrl and ResolveClientUrl methods. Consequently, you can write markup/code like the following:' /The problem is that the above code does not work as expected in a partial view. What's a little confusing is that while the above code compiles and the page, when visited through a browser, renders, the call to Page.ResolveClientUrl returns precisely what you pass in, ~/Content/Images/New.png, in this instance. The browser doesn't know what to do with ~, it presumes it's part of the URL, so it sends the request to the server for the image with the ~ in the URL, which results in a broken image.I did a bit of searching online and found this handy tip from Stephen Walther - Using ResolveUrl in an HTML Helper. In a nutshell, Stephen shows how to create an extension method for the HtmlHelper class that uses the UrlHelper class to resolve a URL. Specifically, Stephen shows how to add an Image extension method to HtmlHelper. I incorporated Stephen's code into my codebase and also created a more generic extension method, which I named ResolveUrl.public static MvcHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url) { var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); return MvcHtmlString.Create(urlHelper.Content(url)); }With this method in place you can resolve a URL in a partial view like so:' /Or you could use Stephen's Html.Image extension method (althoughmy more generic Html.ResolveUrl method could be used in non-image related scenarios where you needed to get a relative URL from a virtual one in a partial view). Thanks for the helpful tip, Stephen!Happy Programming!Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Filp route value in asp.net mvc routes

    - by Herman
    Hi all, I am new to asp.net mvc, so please bear with me. We have the following route dictionary setup. routes.MapRoute( "Default", // Route name "{language}/{controller}/{action}/{id}", // URL with parameters new { language = "en", controller = "Home", action = "Index", id = "" } // Parameter defaults ); for any given page in our app, we to render a link to the a french version of the same page. For example, the page: http://www.example.com/en/home should have link on that page that points to http://www.example.com/fr/home Now I have the following UrlHelper extension method public static string FilpLanguage(this UrlHelper urlHelper) { var data = urlHelper.RequestContext.RouteData; if (System.Threading.Thread.CurrentThread.CurrentCulture == CultureInfo.GetCultureInfoByIetfLanguageTag("en-CA")) data.Values["language"] = "fr"; else data.Values["language"] = "en"; return urlHelper.RouteUrl(data.Values.Where(item => item.Value != null)); } However, calling FilpLanguage on www.example.com/en/home will return the following URL: www.example.com/en/home?current=[,] Am I missing something here? where did the current parameter come from? Thanks in advance.

    Read the article

  • MVC Portable Areas &ndash; Deploying Static Files

    - by Steve Michelotti
    This is the second post in a series related to build and deployment considerations as I’ve been exploring MVC Portable Areas: #1 – Using Web Application Project to build portable areas #2 – Conventions for deploying portable area static files #3 – Portable area static files as embedded resources As I’ve been digging more into portable areas, one of the things I’ve liked best is the deployment story which enables my *.aspx, *.ascx pages to be compiled into the assembly as embedded resources rather than having to maintain all those files separately. In traditional web forms, that was always the thing to prevented developers from utilizing *.ascx user controls across projects (see this post for using portable areas in web forms).  However, though the aspx pages are embedded, the supporting static files (e.g., images, css, javascript) are *not*. Most of the demos available online today tend to brush over this issue and focus solely on the aspx side of things. But to create truly robust portable areas, it’s important to have a good story for these supporting files as well.  I’ve been working with two different approaches so far (of course I’d really like to hear if other people are using alternatives). Scenario For the approaches below, the scenario really isn’t that important. It could be something as trivial as this partial view: 1: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 2: <img src="<%: Url.Content("~/images/arrow.gif") %>" /> Hello World! The point is that there needs to be careful consideration for *any* scenario that links to an external file such as an image, *.css, *.js, etc. In the example shown above, it uses the Url.Content() method to convert to a relative path. But this method won’t necessary work depending on how you deploy your portable area. One approach to address this issue is to build your portable area project with MSDeploy/WebDeploy so that it is packaged properly before incorporating into the host application. All of the *.cs files are removed and the project is ready for xcopy deployment – however, I do *not* need the “Views” folder since all of the mark up has been compiled into the assembly as embedded resources. Now in the host application we create a folder called “Modules” and deploy any portable areas as sub-folders under that: At this point we can add a simple assembly reference to the Widget1.dll sitting in the Modules\Widget1\bin folder. I can now render the portable image in my view like any other portable area. However, the problem with that is that the view results in this:   It couldn’t find arrow.gif because it looked for /images/arrow.gif and it was *actually* located at /images/Modules/Widget1/images/arrow.gif. One solution is to make the physical location of the portable configurable from the perspective of the host like this: 1: <appSettings> 2: <add key="Widget1" value="Modules\Widget1"/> 3: </appSettings> Using the <appSettings> section is a little cheesy but it could be better formalized into its own section. In fact, if were you willing to rely on conventions (e.g., “Modules\{areaName}”) then then config could be eliminated completely. With this config in place, we could create our own Html helper method called Url.AreaContent() that “wraps” the OOTB Url.Content() method while simply pre-pending the area location path: 1: public static string AreaContent(this UrlHelper urlHelper, string contentPath) 2: { 3: var areaName = (string)urlHelper.RequestContext.RouteData.DataTokens["area"]; 4: var areaPath = (string)ConfigurationManager.AppSettings[areaName]; 5:   6: return urlHelper.Content("~/" + areaPath + "/" + contentPath); With these two items in place, we just change our Url.Content() call to Url.AreaContent() like this: 1: <img src="<%: Url.AreaContent("/images/arrow.gif") %>" /> Hello World! and the arrow.gif now renders correctly:     Since we’re just using our own Url.AreaContent() rather than the built-in Url.Content(), this solution works for images, *.css, *.js, or any externally referenced files.  Additionally, any images referenced inside a css file will work provided it’s a relative reference and not an absolute reference. An alternative to this approach is to build the static file into the assembly as embedded resources themselves. I’ll explore this in another post (linked at the top).

    Read the article

  • MVC Portable Areas &ndash; Static Files as Embedded Resources

    - by Steve Michelotti
    This is the third post in a series related to build and deployment considerations as I’ve been exploring MVC Portable Areas: #1 – Using Web Application Project to build portable areas #2 – Conventions for deploying portable area static files #3 – Portable area static files as embedded resources In the last post, I walked through a convention for managing static files.  In this post I’ll discuss another approach to manage static files (e.g., images, css, js, etc.).  With this approach, you *also* compile the static files as embedded resources into the assembly similar to the *.aspx pages. Once again, you can set this to happen automatically by simply modifying your *.csproj file to include the desired extensions so you don’t have to remember every time you add a file: 1: <Target Name="BeforeBuild"> 2: <ItemGroup> 3: <EmbeddedResource Include="**\*.aspx;**\*.ascx;**\*.gif;**\*.css;**\*.js" /> 4: </ItemGroup> 5: </Target> We now need a reliable way to serve up these static files that are embedded in the assembly. There are a couple of ways to do this but one way is to simply create a Resource controller whose job is dedicated to doing this. 1: public class ResourceController : Controller 2: { 3: public ActionResult Index(string resourceName) 4: { 5: var contentType = GetContentType(resourceName); 6: var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); 7:   8: return this.File(resourceStream, contentType); 9: return View(); 10: } 11:   12: private static string GetContentType(string resourceName) 13: { 14: var extention = resourceName.Substring(resourceName.LastIndexOf('.')).ToLower(); 15: switch (extention) 16: { 17: case ".gif": 18: return "image/gif"; 19: case ".js": 20: return "text/javascript"; 21: case ".css": 22: return "text/css"; 23: default: 24: return "text/html"; 25: } 26: } 27: } In order to use this controller, we need to make sure we’ve registered the route in our portable area registration (shown in lines 5-6): 1: public class WidgetAreaRegistration : PortableAreaRegistration 2: { 3: public override void RegisterArea(System.Web.Mvc.AreaRegistrationContext context, IApplicationBus bus) 4: { 5: context.MapRoute("ResourceRoute", "widget1/resource/{resourceName}", 6: new { controller = "Resource", action = "Index" }); 7:   8: context.MapRoute("Widget1", "widget1/{controller}/{action}", new 9: { 10: controller = "Home", 11: action = "Index" 12: }); 13:   14: RegisterTheViewsInTheEmbeddedViewEngine(GetType()); 15: } 16:   17: public override string AreaName 18: { 19: get { return "Widget1"; } 20: } 21: } In my previous post, we relied on a custom Url helper method to find the actual physical path to the static file like this: 1: <img src="<%: Url.AreaContent("/images/arrow.gif") %>" /> Hello World! However, since we are now embedding the files inside the assembly, we no longer have to worry about the physical path. We can change this line of code to this: 1: <img src="<%: Url.Resource("Widget1.images.arrow.gif") %>" /> Hello World! Note that I had to fully quality the resource name (with namespace and physical location) since that is how .NET assemblies store embedded resources. I also created my own Url helper method called Resource which looks like this: 1: public static string Resource(this UrlHelper urlHelper, string resourceName) 2: { 3: var areaName = (string)urlHelper.RequestContext.RouteData.DataTokens["area"]; 4: return urlHelper.Action("Index", "Resource", new { resourceName = resourceName, area = areaName }); 5: } This method gives us the convenience of not having to know how to construct the URL – but just allowing us to refer to the resource name. The resulting html for the image tag is: 1: <img src="/widget1/resource/Widget1.images.arrow.gif" /> so we can always request any image from the browser directly. This is almost analogous to the WebResource.axd file but for MVC. What is interesting though is that we can encapsulate each one of these so that each area can have it’s own set of resources and they are easily distinguished because the area name is the first segment of the route. This makes me wonder if something like this ResourceController should be baked into portable areas itself. I’m definitely interested in anyone has any opinions on it or have taken alternative approaches.

    Read the article

  • ASP.Net MVC 2 Auto Complete Textbox With Custom View Model Attribute & EditorTemplate

    - by SeanMcAlinden
    In this post I’m going to show how to create a generic, ajax driven Auto Complete text box using the new MVC 2 Templates and the jQuery UI library. The template will be automatically displayed when a property is decorated with a custom attribute within the view model. The AutoComplete text box in action will look like the following:   The first thing to do is to do is visit my previous blog post to put the custom model metadata provider in place, this is necessary when using custom attributes on the view model. http://weblogs.asp.net/seanmcalinden/archive/2010/06/11/custom-asp-net-mvc-2-modelmetadataprovider-for-using-custom-view-model-attributes.aspx Once this is in place, make sure you visit the jQuery UI and download the latest stable release – in this example I’m using version 1.8.2. You can download it here. Add the jQuery scripts and css theme to your project and add references to them in your master page. Should look something like the following: Site.Master <head runat="server">     <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>     <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />     <link href="../../css/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />     <script src="../../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>     <script src="../../Scripts/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script> </head> Once this is place we can get started. Creating the AutoComplete Custom Attribute The auto complete attribute will derive from the abstract MetadataAttribute created in my previous post. It will look like the following: AutoCompleteAttribute using System.Collections.Generic; using System.Web.Mvc; using System.Web.Routing; namespace Mvc2Templates.Attributes {     public class AutoCompleteAttribute : MetadataAttribute     {         public RouteValueDictionary RouteValueDictionary;         public AutoCompleteAttribute(string controller, string action, string parameterName)         {             this.RouteValueDictionary = new RouteValueDictionary();             this.RouteValueDictionary.Add("Controller", controller);             this.RouteValueDictionary.Add("Action", action);             this.RouteValueDictionary.Add(parameterName, string.Empty);         }         public override void Process(ModelMetadata modelMetaData)         {             modelMetaData.AdditionalValues.Add("AutoCompleteUrlData", this.RouteValueDictionary);             modelMetaData.TemplateHint = "AutoComplete";         }     } } As you can see, the constructor takes in strings for the controller, action and parameter name. The parameter name will be used for passing the search text within the auto complete text box. The constructor then creates a new RouteValueDictionary which we will use later to construct the url for getting the auto complete results via ajax. The main interesting method is the method override called Process. With the process method, the route value dictionary is added to the modelMetaData AdditionalValues collection. The TemplateHint is also set to AutoComplete, this means that when the view model is parsed for display, the MVC 2 framework will look for a view user control template called AutoComplete, if it finds one, it uses that template to display the property. The View Model To show you how the attribute will look, this is the view model I have used in my example which can be downloaded at the end of this post. View Model using System.ComponentModel; using Mvc2Templates.Attributes; namespace Mvc2Templates.Models {     public class TemplateDemoViewModel     {         [AutoComplete("Home", "AutoCompleteResult", "searchText")]         [DisplayName("European Country Search")]         public string SearchText { get; set; }     } } As you can see, the auto complete attribute is called with the controller name, action name and the name of the action parameter that the search text will be passed into. The AutoComplete Template Now all of this is in place, it’s time to create the AutoComplete template. Create a ViewUserControl called AutoComplete.ascx at the following location within your application – Views/Shared/EditorTemplates/AutoComplete.ascx Add the following code: AutoComplete.ascx <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <%     var propertyName = ViewData.ModelMetadata.PropertyName;     var propertyValue = ViewData.ModelMetadata.Model;     var id = Guid.NewGuid().ToString();     RouteValueDictionary urlData =         (RouteValueDictionary)ViewData.ModelMetadata.AdditionalValues.Where(x => x.Key == "AutoCompleteUrlData").Single().Value;     var url = Mvc2Templates.Views.Shared.Helpers.RouteHelper.GetUrl(this.ViewContext.RequestContext, urlData); %> <input type="text" name="<%= propertyName %>" value="<%= propertyValue %>" id="<%= id %>" class="autoComplete" /> <script type="text/javascript">     $(function () {         $("#<%= id %>").autocomplete({             source: function (request, response) {                 $.ajax({                     url: "<%= url %>" + request.term,                     dataType: "json",                     success: function (data) {                         response(data);                     }                 });             },             minLength: 2         });     }); </script> There is a lot going on in here but when you break it down it’s quite simple. Firstly, the property name and property value are retrieved through the model meta data. These are required to ensure that the text box input has the correct name and data to allow for model binding. If you look at line 14 you can see them being used in the text box input creation. The interesting bit is on line 8 and 9, this is the code to retrieve the route value dictionary we added into the model metada via the custom attribute. Line 11 is used to create the url, in order to do this I created a quick helper class which looks like the code below titled RouteHelper. The last bit of script is the code to initialise the jQuery UI AutoComplete control with the correct url for calling back to our controller action. RouteHelper using System.Web.Mvc; using System.Web.Routing; namespace Mvc2Templates.Views.Shared.Helpers {     public static class RouteHelper     {         const string Controller = "Controller";         const string Action = "Action";         const string ReplaceFormatString = "REPLACE{0}";         public static string GetUrl(RequestContext requestContext, RouteValueDictionary routeValueDictionary)         {             RouteValueDictionary urlData = new RouteValueDictionary();             UrlHelper urlHelper = new UrlHelper(requestContext);                          int i = 0;             foreach(var item in routeValueDictionary)             {                 if (item.Value == string.Empty)                 {                     i++;                     urlData.Add(item.Key, string.Format(ReplaceFormatString, i.ToString()));                 }                 else                 {                     urlData.Add(item.Key, item.Value);                 }             }             var url = urlHelper.RouteUrl(urlData);             for (int index = 1; index <= i; index++)             {                 url = url.Replace(string.Format(ReplaceFormatString, index.ToString()), string.Empty);             }             return url;         }     } } See it in action All you need to do to see it in action is pass a view model from your controller with the new AutoComplete attribute attached and call the following within your view: <%= this.Html.EditorForModel() %> NOTE: The jQuery UI auto complete control expects a JSON string returned from your controller action method… as you can’t use the JsonResult to perform GET requests, use a normal action result, convert your data into json and return it as a string via a ContentResult. If you download the solution it will be very clear how to handle the controller and action for this demo. The full source code for this post can be downloaded here. It has been developed using MVC 2 and Visual Studio 2010. As always, I hope this has been interesting/useful. Kind Regards, Sean McAlinden.

    Read the article

  • Syntax to specify Namespace when using helper.RouteUrl

    - by B Z
    I am using Asp.Net MVC 2 - RC w/ Areas. I am receiving an ambigious controller name exception due to having same controller name in two different areas. I've read Phil Haack's post I can't figure out the syntax when trying to use UrlHelper (I have an extensions class). e.g. public static string MyAreaHome(this UrlHelper helper) { return helper.RouteUrl("ARoute", new { controller = "Home", action = "Index" }); } I've tried the obvious of adding namespace="mynamespace" but that didn't work, it just added the namespace to the url. Thanks for any help.

    Read the article

  • MVC Routes - How to get a URL?

    - by Seattle Leonard
    In my current project we have a notification system. When an oject is added to another objects collection, an email is sent to those who are subscibed to the parent object. This happens on the object layer and not in the View or Controller. Here's the problem: Although we can say who created what with what information in the email, we cannot embed links to those objects in the email because in the object layer there is no access to a UrlHelper. To construct a UrlHelper you need a RequestContext, which again does not exist on the object layer. Question: I want to make a helper class to create the url's for me. How can I create an object that will generate these urls without a request context? Is it possible?

    Read the article

  • Error when accessing IIS 7 server variable from ASP.Net MVC

    - by StephSpr
    I have an ASP.Net MVC application which works fine on IIS 6.0 / Windows Server 2003. When installed on IIS 7.5 / Windows Server 2008 (integrated mode), it works but when the application attempts to generate an URL, it runs into the following error: [NullReferenceException: Object reference not set to an instance of an object.] System.Web.HttpServerVarsCollection.Get(String name) +10960764 System.Web.Mvc.PathHelpers.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath) +345 System.Web.Mvc.PathHelpers.GenerateClientUrl(HttpContextBase httpContext, String contentPath) +80 System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues) +256 System.Web.Mvc.UrlHelper.Action(String actionName, String controllerName, RouteValueDictionary routeValues) +36 It looks like IIS7 fails to return the server name. There should be a configuration to set, but I couldn't find anything like that. Do you have any idea to fix this issue ? Thanks,

    Read the article

  • LinkBuilder.BuildUrlFromExpression not working anymore in .Net 4 / VS 2010 ?

    - by Mose
    Hi, I recently migrating my ASP.Net MVC 1 application from VS.Net 2008 / C# 3.5 to VS.NET 2010 / C# 4.0. I massively used a builder to get URL strings from the strongly typed calls. It looks like this : // sample call : string toSamplePage = Url.To<SampleController>(c => c.Page(parameter1, parameter2)); the code is added as an extension to the default UrlHelper : public static string To<Tcontroller>(UrlHelper helper, Expression<Action<Tcontroller>> action) where Tcontroller : Controller { // based on Microsoft.Web.Mvc.dll LinkBuilder return LinkBuilder.BuildUrlFromExpression<Tcontroller>(helper.RequestContext, helper.RouteCollection, action); } The only problem of this, is the reference to Microsoft.Web.Mvc dll, but the gain in readability was worth it. Problem : it does not work anymore, return (null) whatever the parameters. Questions : is there a better way now to build links from an expression ? (yes I tried to google it without success) is there a trick to have the former LinkBuilder.BuildUrlFromExpression works ? I tried to recompile it into C# 4.0, but the problem is that it implies working on my own compilated version of System.Web.Mvc which is not an option. I'm currently trying to migrate to MVC 2 but I still have issues... Waiting for your suggestions...

    Read the article

  • ASP MVC.Net 3 RC2 bug ?

    - by Jarek Waliszko
    Hello, so far I've been using ASP.Net 3 BETA. Everything was working fine till the update to RC2 version. Of course I've read ScottGu's article about RC2. My problem is following. Basically I have 2 controllers: public class DynamicPageController : Controller { public ActionResult Redirect(string resource, int? pageNumber, int? id) { } } public class SystemController : Controller { public ActionResult Index() { } } In the Globals.asax I have routes like this: public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "SystemRoute", "System/{action}", new { controller = "System", action = "Index" } ); routes.MapRoute( "PageRoute", "{resource}/{id}/{pageNumber}", new { controller = "DynamicPage", action = "Redirect", resource = UrlParameter.Optional, pageNumber = UrlParameter.Optional, id = UrlParameter.Optional } ); } In the code, I have simple link creation: System.Web.Mvc.UrlHelper u = new System.Web.Mvc.UrlHelper(context); string url = u.Action("Index", "System"); and the url is "/my_app/System" in both versions (BETA and RC2) But the code below (the syntax is the same as above, only controller and action names are different): string url = u.Action("Redirect", "DynamicPage", new RouteValueDictionary(new { resource = "Home" })); gives url which is null in RC2. It should be (and in fact in BETA was) "/my_app/Home" Why ? Is it a bug ? How can I create url for my "DynamicPage" controller ? Regards BTW: From where can I now download ASP.Mvc BETA version along with ASP.Net Web Pages 1.0 installers ? Since RC2 announcement I have problems finding mentioned 2 installers. Normally I would upgrade my code but this issue described above makes me stay with BETA for a while, since I have no time for migration and testing everything now.

    Read the article

  • Kooboo CMS 2.1.1.0 released

    New features Add new API RssUrl to generate RSS link, this is an extension to UrlHelper. Add possibility to index and search attachment content on Lucene full text search engine, some of the attachment requires ifilter component from Microsoft. Supported file attachments include: .docx, .docm, .pptx, .pptm, .xlsx, .xlsm, .xlsb, .zip, .one, .vdx, .vsd, .vss, .vst, .vdx, .vsx, and .vtx.Please download and install ifilter from: http://www.microsoft.com/downloads/details.aspx?FamilyId=60C92A37-719C-4077-B5C6-CAC34F4227CC&displaylang=enFor...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

1 2  | Next Page >