Search Results

Search found 798 results on 32 pages for 'helpers'.

Page 1/32 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • 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

  • Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

    - by SeanMcAlinden
    There are a number of ways of implementing a pattern for using custom view model attributes, the following is similar to something I’m using at work which works pretty well. The classes I’m going to create are really simple: 1. Abstract base attribute 2. Custom ModelMetadata provider which will derive from the DataAnnotationsModelMetadataProvider   Base Attribute MetadataAttribute using System; using System.Web.Mvc; namespace Mvc2Templates.Attributes {     /// <summary>     /// Base class for custom MetadataAttributes.     /// </summary>     public abstract class MetadataAttribute : Attribute     {         /// <summary>         /// Method for processing custom attribute data.         /// </summary>         /// <param name="modelMetaData">A ModelMetaData instance.</param>         public abstract void Process(ModelMetadata modelMetaData);     } } As you can see, the class simple has one method – Process. Process accepts the ModelMetaData which will allow any derived custom attributes to set properties on the model meta data and add items to its AdditionalValues collection.   Custom Model Metadata Provider For a quick explanation of the Model Metadata and how it fits in to the MVC 2 framework, it is basically a set of properties that are usually set via attributes placed above properties on a view model, for example the ReadOnly and HiddenInput attributes. When EditorForModel, DisplayForModel or any of the other EditorFor/DisplayFor methods are called, the ModelMetadata information is used to determine how to display the properties. All of the information available within the model metadata is also available through ViewData.ModelMetadata. The following class derives from the DataAnnotationsModelMetadataProvider built into the mvc 2 framework. I’ve overridden the CreateMetadata method in order to process any custom attributes that may have been placed above a property in a view model.   CustomModelMetadataProvider using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Mvc2Templates.Attributes; namespace Mvc2Templates.Providers {     public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider     {         protected override ModelMetadata CreateMetadata(             IEnumerable<Attribute> attributes,             Type containerType,             Func<object> modelAccessor,             Type modelType,             string propertyName)         {             var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);               attributes.OfType<MetadataAttribute>().ToList().ForEach(x => x.Process(modelMetadata));               return modelMetadata;         }     } } As you can see, once the model metadata is created through the base method, a check for any attributes deriving from our new abstract base attribute MetadataAttribute is made, the Process method is then called on any existing custom attributes with the model meta data for the property passed in.   Hooking it up The last thing you need to do to hook it up is set the new CustomModelMetadataProvider as the current ModelMetadataProvider, this is done within the Global.asax Application_Start method. Global.asax protected void Application_Start()         {             AreaRegistration.RegisterAllAreas();               RegisterRoutes(RouteTable.Routes);               ModelMetadataProviders.Current = new CustomModelMetadataProvider();         }   In my next post, I’m going to demonstrate a cool custom attribute that turns a textbox into an ajax driven AutoComplete text box. Hope this is useful. Kind Regards, Sean McAlinden.

    Read the article

  • Procurement Search Helpers

    - by Oracle_EBS
    To access all our Procurement Search Helpers see Doc ID 1391332.2 our Procurement Information Center Index, then click on Purchasing under Procurement Suite. Here you will see links to our Procurement Search Helpers: Search Helpers provide a collection of solutions based on the symptoms you enter. Try these before logging a Service Request.  If you are not sure how to use Search Helpers, click on 'About this Note' in each document. Current Procurement Search Helpers: Doc ID Search Helper Title 1361856.1  EBS : Purchase Order and Requisition Approval Search Helper (In Process or Incomplete Status) 1377764.1 EBS : PO Output for Communication / Supplier Notification Issues Search Helper 1364360.1 EBS : Requisition To Purchase Order Search Helper 1369663.1 EBS : Purchase Document Open Interface and API Search Helper 1391970.1 EBS : Search Helper for RVTII-060 Errors in Receiving 1394392.1 EBS : Purchasing Buyer Work Center Search Helper 1470034.1 EBS : Document Control Issues Search Helper

    Read the article

  • Creating Custom HTML Helpers in ASP.NET MVC

    - by Shravan
    ASP.NET MVC provides many built-in HTML Helpers.  With help of HTML Helpers we can reduce the amount of typing of HTML tags for creating a HTML page. For example we use Html.TextBox() helper method it generates html input textbox. Write the following code snippet in MVC View: <%=Html.TextBox("txtName",20)%> It generates the following html in output page: <input id="txtName" name="txtName" type="text" value="20" /> List of built-in HTML Helpers provided by ASP.NET MVC. ActionLink() - Links to an action method. BeginForm() - Marks the start of a form and links to the action method that renders the form. CheckBox() - Renders a check box. DropDownList() - Renders a drop-down list. Hidden() - Embeds information in the form that is not rendered for the user to see. ListBox() - Renders a list box. Password() - Renders a text box for entering a password. RadioButton() - Renders a radio button.TextArea() - Renders a text area (multi-line text box). TextBox () - Renders a text box. How to develop our own Custom HTML Helpers? For developing custom HTML helpers the simplest way is to write an extension method for the HtmlHelper class. See the below code, it builds a custom Image HTML Helper for generating image tag. Read The Remaing Blog Post @ http://theshravan.net/blog/creating-custom-html-helpers-in-asp-net-mvc/

    Read the article

  • Oracle E-Business Products New Search Helpers for Guided Resolution of Customer Issues

    - by user793044
    Oracle E-Business Proactive Support has created many new guided resolution documents that you may find helpful in resolving issues in your EBS applications.  These new documents are called “Search Helpers” and they guide you through your issue to a solution.  They are meant to be an easy and fast method to finding a relevant, complete solution. Hundreds of notes and service requests were reviewed and the best solutions to these known issues were selected.  For some issues, notes were updated to better clarify the solution.  In other cases, if a note with a solution did not already exist, one was created. You start the process by selecting the scenario you have encountered.  You may have received an error message, or there may be a particular area of the application in which you have encountered an issue.  Based on your selection of the issue, the Search Helper will present one or more additional possible symptoms.  When you have selected from both of these two sections, you are then presented with one or more articles known to have fully solved this issue in the past.  Several EBS products have produced Search Helpers documents.  Take a look at Doc ID 1501724.1 for an index of the current EBS Search Helpers.  Here is an example of a Search Helper from the Receivables Transactions area: After selecting the Functional Area of "Entering / Updating Transactions" a list of Known Symptoms is presented: And, when "Transaction numbers are not in sequence" is selected, a solution link is provided for Document ID 197212.1: How To Setup Gapless Document Sequencing in Receivables. The EBS applications that currently have published Search Helpers are: Advanced Pricing Applications Technology Configurator General Ledger Human Capital Management Inventory Management Order Management Payables Process Manufacturing Purchasing Receivables Shipping Value Chain Planning

    Read the article

  • Implementing Role based Helpers

    - by Cynics
    So my question is how would you implement your handwritten Helpers based on the role of current user. Would it be efficient to change the behaviour at request time? e.g. the Helper somehow figures out the role of user, and include the proper SubModule? module ApplicationHelper module LoggedInHelper # Some functions end module GuestHelper # The Same functions end # If User is Guest then include GuestHelper # If User is LoggedIn then include LoggedInHelper end Is it efficient this way? is it rails way? I've got a whole bunch of function that act like this, and I don't want to wrap every single one of them in an if statement def menu_actions if current_user.nil? # User is guest { "Log in" => link_to "Login", "/login" } else # User is Logged In { "Log out" => link_to "Logout", "/logout" } end end Thank you for your time and thoughts.

    Read the article

  • New and Improved Search Helpers Now Procurement Assistants!

    - by LuciaC
    Check out the new and improved Procurement Assistants (formerly Search Helpers). Let us guide you simply to Issue Resolution.  To access all our Procurement Search Helpers see Doc ID 1391694.2 our Procurement Information Center. Here you will see links to our Procurement Search Helpers: Assistants provide a collection of solutions based on the symptoms you enter. For example simply choose the radial button that pertains to your issue, as shown here: Then choose the additional symptom(s) that pertain and potential solution documents will be returned as shown here: Try these before logging a Service Request. Current Procurement Assistants: Doc ID Title 1361856.1     Assistant: Oracle Purchasing - Purchase Order and Requisition Approval (Search Helper) 1377764.1    Assistant: Oracle Purchasing PO Output for Communication / Supplier Notification Issues (Search Helper) 1364360.1    Assistant: Oracle Purchasing Requisition To Purchase Order (Search Helper) 1369663.1    Assistant: Oracle Purchasing Purchase Document Open Interface and API (Search Helper) 1391970.1    Assistant: Oracle Inventory Management RVTII-060 Errors in Receiving (Search Helper) 1394392.1    Assistant: Oracle Purchasing Buyer Work Center Search Helper (Search Helper) 1470034.1    Assistant: Oracle Purchasing - Document Control : Cancel and Close

    Read the article

  • ASP.NET MVC 2: Strongly Typed Html Helpers

    In this article, Scott examines the usage of Strongly Typed Html Helpers included with ASP.NET MVC 2. He begins with a short description of the existing HTML Helper method in ASP.NET MVC 1 and discusses the new methods, providing screenshots and a detailed listing of these new methods.

    Read the article

  • Writing an unthemed view while still using Orchard shapes and helpers

    - by Bertrand Le Roy
    This quick tip will show how you can write a custom view for a custom controller action in Orchard that does not use the current theme, but that still retains the ability to use shapes, as well as zones, Script and Style helpers. The controller action, first, needs to opt out of theming: [Themed(false)] public ActionResult Index() {} .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Then, we still want to use a shape as the view model, because Clay is so awesome: private readonly dynamic _shapeFactory; public MyController(IShapeFactory shapeFactory) { _shapeFactory = shapeFactory; } [Themed(false)] public ActionResult Index() { return View(_shapeFactory.MyShapeName( Foo: 42, Bar: "baz" )); } As you can see, we injected a shape factory, and that enables us to build our shape from our action and inject that into the view as the model. Finally, in the view (that would in Views/MyController/Index.cshtml here), just use helpers as usual. The only gotcha is that you need to use “Layout” in order to declare zones, and that two of those zones, Head and Tail, are mandatory for the top and bottom scripts and stylesheets to be injected properly. Names are important here. @{ Style.Include("somestylesheet.css"); Script.Require("jQuery"); Script.Include("somescript.js"); using(Script.Foot()) { <script type="text/javascript"> $(function () { // Do stuff }) </script> } } <!DOCTYPE html> <html> <head> <title>My unthemed page</title> @Display(Layout.Head) </head> <body> <h1>My unthemed page</h1> <div>@Model.Foo is the answer.</div> </body> @Display(Layout.Tail) </html> Note that if you define your own zones using @Display(Layout.SomeZone) in your view, you can perfectly well send additional shapes to them from your controller action, if you injected an instance of IWorkContextAccessor: _workContextAccessor.GetContext().Layout .SomeZone.Add(_shapeFactory.SomeOtherShape()); Of course, you’ll need to write a SomeOtherShape.cshtml template for that shape but I think this is pretty neat.

    Read the article

  • Rails: how do you access RESTful helpers?

    - by Ethan
    I'm trying to work through this guide to Rails routing, but I got stuck in section 3.3: Creating a RESTful route will also make available a pile of helpers within your application and then they list some helpers like photos_url, photos_path, etc. My questions: Where can I find the complete list of helpers that is "made available?" Is there a way to call the helpers in the console? I created an app, then opened up the console with script/console. I tried to call one of the helpers on the console like this: >> entries_url But got: NameError: undefined local variable or method `entries_url' for #<Object:0x349a4> from (irb):8

    Read the article

  • How to add/register helpers with Zend Framework

    - by manyxcxi
    I'm just starting out with Zend Framework and am having issues using Zend_Controller_Action_HelperBroker::addPath() to add helpers. I'm not sure if my classes are named incorrectly, I'm giving it the wrong prefix, or what I'm doing wrong so I will post the code and file structure and get out of the way. In Bootstrap.php public function __construct($application) { ... // This works with a manual include_once('../application/plugins/helpers/Csrf.php'); //Zend_Controller_Action_HelperBroker::addHelper(new Application_Controller_Action_Helper_Csrf()); // This isn't picking up my helper class automagically Zend_Controller_Action_HelperBroker::addPath('../application/plugins/helpers','Application_Controller_Action_Helper'); ... } In application/plugins/helpers/Csrf.php class Application_Controller_Action_Helper_Csrf extends Zend_Controller_Action_Helper_Abstract { ... } My directory tree: / application/ ... plugins/ helpers/ Csrf.php CsrfProtect.php ...

    Read the article

  • How to use Zend_Controller_Action_HelperBroker::addPath to add helpers

    - by manyxcxi
    I'm just starting out with Zend Framework and am having issues using the addPath to add helpers. I'm not sure if my classes are named incorrectly, I'm giving it the wrong prefix, or what I'm doing wrong so I will post the code and file structure and get out of the way. In Bootstrap.php public function __construct($application) { ... // This works with a manual include_once('../application/plugins/helpers/Csrf.php'); //Zend_Controller_Action_HelperBroker::addHelper(new Application_Controller_Action_Helper_Csrf()); // This isn't picking up my helper class automagically Zend_Controller_Action_HelperBroker::addPath('../application/plugins/helpers','Application_Controller_Action_Helper'); ... } In application/plugins/helpers/Csrf.php class Application_Controller_Action_Helper_Csrf extends Zend_Controller_Action_Helper_Abstract { ... } My directory tree / application/ ... plugins/ helpers/ Csrf.php CsrfProtect.php ...

    Read the article

  • Anti-Forgery Request Helpers for ASP.NET MVC and jQuery AJAX

    - by Dixin
    Background To secure websites from cross-site request forgery (CSRF, or XSRF) attack, ASP.NET MVC provides an excellent mechanism: The server prints tokens to cookie and inside the form; When the form is submitted to server, token in cookie and token inside the form are sent in the HTTP request; Server validates the tokens. To print tokens to browser, just invoke HtmlHelper.AntiForgeryToken():<% using (Html.BeginForm()) { %> <%: this.Html.AntiForgeryToken(Constants.AntiForgeryTokenSalt)%> <%-- Other fields. --%> <input type="submit" value="Submit" /> <% } %> This invocation generates a token then writes inside the form:<form action="..." method="post"> <input name="__RequestVerificationToken" type="hidden" value="J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP" /> <!-- Other fields. --> <input type="submit" value="Submit" /> </form> and also writes into the cookie: __RequestVerificationToken_Lw__= J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. In the server side, [ValidateAntiForgeryToken] attribute is used to specify the controllers or actions to validate them:[HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult Action(/* ... */) { // ... } This is very productive for form scenarios. But recently, when resolving security vulnerabilities for Web products, some problems are encountered. Specify validation on controller (not on each action) The server side problem is, It is expected to declare [ValidateAntiForgeryToken] on controller, but actually it has be to declared on each POST actions. Because POST actions are usually much more then controllers, this is a little crazy Problem Usually a controller contains actions for HTTP GET and actions for HTTP POST requests, and usually validations are expected for HTTP POST requests. So, if the [ValidateAntiForgeryToken] is declared on the controller, the HTTP GET requests become invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller // One [ValidateAntiForgeryToken] attribute. { [HttpGet] public ActionResult Index() // Index() cannot work. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If browser sends an HTTP GET request by clicking a link: http://Site/Some/Index, validation definitely fails, because no token is provided. So the result is, [ValidateAntiForgeryToken] attribute must be distributed to each POST action:public class SomeController : Controller // Many [ValidateAntiForgeryToken] attributes. { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } This is a little bit crazy, because one application can have a lot of POST actions. Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one for each POST action), the following ValidateAntiForgeryTokenAttribute wrapper class can be helpful, where HTTP verbs can be specified:[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) : this(verbs, null) { } public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } public void OnAuthorization(AuthorizationContext filterContext) { string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } When this attribute is declared on controller, only HTTP requests with the specified verbs are validated:[ValidateAntiForgeryTokenWrapper(HttpVerbs.Post, Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { // GET actions are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all POST actions. Maybe it would be nice if HTTP verbs can be specified on the built-in [ValidateAntiForgeryToken] attribute, which is easy to implemented. Submit token via AJAX The browser side problem is, if server side turns on anti-forgery validation for POST, then AJAX POST requests will fail be default. Problem For AJAX scenarios, when request is sent by jQuery instead of form:$.post(url, { productName: "Tofu", categoryId: 1 // Token is not posted. }, callback); This kind of AJAX POST requests will always be invalid, because server side code cannot see the token in the posted data. Solution The tokens are printed to browser then sent back to server. So first of all, HtmlHelper.AntiForgeryToken() must be called somewhere. Now the browser has token in HTML and cookie. Then jQuery must find the printed token in the HTML, and append token to the data before sending:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated into a tiny jQuery plugin:/// <reference path="jquery-1.4.2.js" /> (function ($) { $.getAntiForgeryToken = function (tokenWindow, appPath) { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. tokenWindow = tokenWindow && typeof tokenWindow === typeof window ? tokenWindow : window; appPath = appPath && typeof appPath === "string" ? "_" + appPath.toString() : ""; // The name attribute is either __RequestVerificationToken, // or __RequestVerificationToken_{appPath}. tokenName = "__RequestVerificationToken" + appPath; // Finds the <input type="hidden" name={tokenName} value="..." /> from the specified. // var inputElements = $("input[type='hidden'][name='__RequestVerificationToken" + appPath + "']"); var inputElements = tokenWindow.document.getElementsByTagName("input"); for (var i = 0; i < inputElements.length; i++) { var inputElement = inputElements[i]; if (inputElement.type === "hidden" && inputElement.name === tokenName) { return { name: tokenName, value: inputElement.value }; } } return null; }; $.appendAntiForgeryToken = function (data, token) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } // Gets token from current window by default. token = token ? token : $.getAntiForgeryToken(); // $.getAntiForgeryToken(window). data = data ? data + "&" : ""; // If token exists, appends {token.name}={token.value} to data. return token ? data + encodeURIComponent(token.name) + "=" + encodeURIComponent(token.value) : data; }; // Wraps $.post(url, data, callback, type). $.postAntiForgery = function (url, data, callback, type) { return $.post(url, $.appendAntiForgeryToken(data), callback, type); }; // Wraps $.ajax(settings). $.ajaxAntiForgery = function (settings) { settings.data = $.appendAntiForgeryToken(settings.data); return $.ajax(settings); }; })(jQuery); In most of the scenarios, it is Ok to just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() with $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. There might be some scenarios of custom token. Here $.appendAntiForgeryToken() is provided:data = $.appendAntiForgeryToken(data, token); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); And there are scenarios that the token is not in the current window. For example, an HTTP POST request can be sent by iframe, while the token is in the parent window. Here window can be specified for $.getAntiForgeryToken():data = $.appendAntiForgeryToken(data, $.getAntiForgeryToken(window.parent)); // Token is already in data. No need to invoke $.postAntiForgery(). $.post(url, data, callback); If you have better solution, please do tell me.

    Read the article

  • Knockout with ASP.Net MVC2 - HTML Extension Helpers for input controls

    - by Renso
    Goal: Defining Knockout-style input controls can be tedious and also may be something that you may find obtrusive, mixing your HTML with data bind syntax as well as binding your aspx, ascx files to Knockout. The goal is to make specifying Knockout specific HTML tags easy, seamless really, as well as being able to remove references to Knockout easily. Environment considerations: ASP.Net MVC2 or later Knockoutjs.js How to:     public static class HtmlExtensions     {         public static string DataBoundCheckBox(this HtmlHelper helper, string name, bool isChecked, object htmlAttributes)         {             var builder = new TagBuilder("input");             var dic = new RouteValueDictionary(htmlAttributes) { { "data-bind", String.Format("checked: {0}", name) } };             builder.MergeAttributes(dic);             builder.MergeAttribute("type", @"checkbox");             builder.MergeAttribute("name", name);             builder.MergeAttribute("value", @"true");             if (isChecked)             {                 builder.MergeAttribute("checked", @"checked");             }             return builder.ToString(TagRenderMode.SelfClosing);         }         public static MvcHtmlString DataBoundSelectList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, String optionLabel)         {             var attrProperties = new StringBuilder();             attrProperties.Append(String.Format("optionsText: '{0}'", name));             if (!String.IsNullOrEmpty(optionLabel)) attrProperties.Append(String.Format(", optionsCaption: '{0}'", optionLabel));             attrProperties.Append(String.Format(", value: {0}", name));             var dic = new RouteValueDictionary { { "data-bind", attrProperties.ToString() } };             return helper.DropDownList(name, selectList, optionLabel, dic);         }         public static MvcHtmlString DataBoundSelectList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, String optionLabel, object htmlAttributes)         {             var attrProperties = new StringBuilder();             attrProperties.Append(String.Format("optionsText: '{0}'", name));             if (!String.IsNullOrEmpty(optionLabel)) attrProperties.Append(String.Format(", optionsCaption: '{0}'", optionLabel));             attrProperties.Append(String.Format(", value: {0}", name));             var dic = new RouteValueDictionary(htmlAttributes) {{"data-bind", attrProperties}};             return helper.DropDownList(name, selectList, optionLabel, dic);         }         public static String DataBoundSelectList(this HtmlHelper helper, String options, String optionsText, String value)         {             return String.Format("<select data-bind=\"options: {0},optionsText: '{1}',value: {2}\"></select>", options, optionsText, value);         }         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextBox(name, value, dic);         }         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, string observable, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", observable));             return helper.TextBox(name, value, dic);         }         public static MvcHtmlString DataBoundTextArea(this HtmlHelper helper, string name, string value, int rows, int columns, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextArea(name, value, rows, columns, dic);         }         public static MvcHtmlString DataBoundTextArea(this HtmlHelper helper, string name, string observable, string value, int rows, int columns, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", observable));             return helper.TextArea(name, value, rows, columns, dic);         }         public static string BuildUrlFromExpression<T>(this HtmlHelper helper, Expression<Action<T>> action)         {             var values = CreateRouteValuesFromExpression(action);             var virtualPath = helper.RouteCollection.GetVirtualPath(helper.ViewContext.RequestContext, values);             if (virtualPath != null)             {                 return virtualPath.VirtualPath;             }             return null;         }         public static string ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> action, string linkText)         {             return helper.ActionLink(action, linkText, null);         }         public static string ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> action, string linkText, object htmlAttributes)         {             var values = CreateRouteValuesFromExpression(action);             var controllerName = (string)values["controller"];             var actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.ActionLink(linkText, actionName, controllerName, values, new RouteValueDictionary(htmlAttributes)).ToHtmlString();         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action)         {             return helper.Form(action, FormMethod.Post);         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action, FormMethod method)         {             var values = CreateRouteValuesFromExpression(action);             string controllerName = (string)values["controller"];             string actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.BeginForm(actionName, controllerName, values, method);         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action, FormMethod method, object htmlAttributes)         {             var values = CreateRouteValuesFromExpression(action);             string controllerName = (string)values["controller"];             string actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.BeginForm(actionName, controllerName, values, method, new RouteValueDictionary(htmlAttributes));         }         public static string VertCheckBox(this HtmlHelper helper, string name, bool isChecked)         {             return helper.CustomCheckBox(name, isChecked, null);         }          public static string CustomCheckBox(this HtmlHelper helper, string name, bool isChecked, object htmlAttributes)         {             TagBuilder builder = new TagBuilder("input");             builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));             builder.MergeAttribute("type", "checkbox");             builder.MergeAttribute("name", name);             builder.MergeAttribute("value", "true");             if (isChecked)             {                 builder.MergeAttribute("checked", "checked");             }             return builder.ToString(TagRenderMode.SelfClosing);         }         public static string Script(this HtmlHelper helper, string script, object scriptAttributes)         {             var pathForCRMScripts = ScriptsController.GetPathForCRMScripts();             if (ScriptOptimizerConfig.EnableMinimizedFileLoad)             {                 string newPathForCRM = pathForCRMScripts + "Min/";                 ScriptsController.ServerPathMapper = new ServerPathMapper();                 string fullPath = ScriptsController.ServerMapPath(newPathForCRM);                 if (!File.Exists(fullPath + script))                     return null;                 if (!Directory.Exists(fullPath))                     return null;                 pathForCRMScripts = newPathForCRM;             }             var builder = new TagBuilder("script");             builder.MergeAttributes(new RouteValueDictionary(scriptAttributes));             builder.MergeAttribute("type", @"text/javascript");             builder.MergeAttribute("src", String.Format("{0}{1}", pathForCRMScripts.Replace("~", String.Empty), script));             return builder.ToString(TagRenderMode.SelfClosing);         }         private static RouteValueDictionary CreateRouteValuesFromExpression<T>(Expression<Action<T>> action)         {             if (action == null)                 throw new InvalidOperationException("Action must be provided");             var body = action.Body as MethodCallExpression;             if (body == null)             {                 throw new InvalidOperationException("Expression must be a method call");             }             if (body.Object != action.Parameters[0])             {                 throw new InvalidOperationException("Method call must target lambda argument");             }             // This will build up a RouteValueDictionary containing the controller name, action name, and any             // parameters passed as part of the "action" parameter.             string name = body.Method.Name;             string controllerName = typeof(T).Name;             if (controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))             {                 controllerName = controllerName.Remove(controllerName.Length - 10, 10);             }             var values = BuildParameterValuesFromExpression(body) ?? new RouteValueDictionary();             values.Add("controller", controllerName);             values.Add("action", name);             return values;         }         private static RouteValueDictionary BuildParameterValuesFromExpression(MethodCallExpression call)         {             // Build up a RouteValueDictionary containing parameter names as keys and parameter values             // as values based on the MethodCallExpression passed in.             var values = new RouteValueDictionary();             ParameterInfo[] parameters = call.Method.GetParameters();             // If the passed in method has no parameters, just return an empty dictionary.             if (parameters.Length == 0)             {                 return values;             }             for (int i = 0; i < parameters.Length; i++)             {                 object parameterValue;                 Expression expression = call.Arguments[i];                 // If the current parameter is a constant, just use its value as the parameter value.                 var constant = expression as ConstantExpression;                 if (constant != null)                 {                     parameterValue = constant.Value;                 }                 else                 {                     // Otherwise, compile and execute the expression and use that as the parameter value.                     var function = Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object)),                                                                    new ParameterExpression[0]);                     try                     {                         parameterValue = function.Compile()();                     }                     catch                     {                         parameterValue = null;                     }                 }                 values.Add(parameters[i].Name, parameterValue);             }             return values;         }     }   Some observations: The first two DataBoundSelectList overloaded methods are specifically built to load the data right into the drop down box as part of the HTML response stream rather than let Knockout's engine populate the options client-side. The third overloaded method does it client-side via the viewmodel. The first two overloads can be done when you have no requirement to add complex JSON objects to your lists. Furthermore, why render and parse the JSON object when you can have it all built and rendered server-side like any other list control.

    Read the article

  • razor intellisense not working on VS2010 for microsoft.web.helpers

    - by pomarc
    I have VS2010 Premium,.NET4.0, MVC3 Tools Update. I've nugetted microsoft-web-helpers successfully. I cannot get @razor intellisense to recognize the microsoft.web.helpers classes. They do work correctely at runtime, i.e. @Twitter.profile shows a profile, but at design time the statent is seen as an error and no members are shown after "." I've tried to add <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> to the <assemblies> element in web.config, but it didn't help. Any idea? thanks.

    Read the article

  • Active Mailer doesn't have the application helpers when used with delayed_job v.2

    - by Savvas
    So if I try sending an email with action mailer directly, I can use all application helpers like url_for, content_for etc, but when I try to do the exact same action [sending email] with delayed_job [send_later] I getting a delayed job fail, of undefined function content_for etc, so it is like no helpers are loaded in my ActionMailer. I am using rails 2.3.8, active_mailer 2.3.8 and delayed_job 2.0.3 Thanks!!

    Read the article

  • How to add a view helper directory (zend framework)

    - by Cédric Girard
    Hi, I begin with ZF (1.9.7), and I want to use View Helpers from a library shared between all my projects. But I can't find how to add it directory to the helpers path. My herpers works fines when I put them in application's helpers path. Here is the error, where I find the path to ZF helpers, and path to the applications ones. object(ArrayObject)#71 (3) { ["exception"]=> object(Zend_Loader_PluginLoader_Exception)#70 (6) { ["message:protected"]=> string(151) "Plugin by name 'Voo' was not found in the registry; used paths: Zend_View_Helper_: Zend/View/Helper/;C:/ZendStd/www/applis/VOO4_PROJECTX/views\helpers/" ["string:private"]=> string(0) "" ["code:protected"]=> int(0) ["file:protected"]=> string(89) "C:\Program Files\Zend\ZendServer\share\ZendFramework\library\Zend\Loader\PluginLoader.php" ["line:protected"]=> int(401) Best regards Cédric

    Read the article

  • Trying to extend ActionView::Helpers::FormBuilder

    - by nibbo
    Hello I am trying to DRY up some code by moving some logic into the FormBuilder. After reading the documentation about how to select and alternative form builder the logical solution for me seemed to be something like this. In the view <% form_for @event, :builder => TestFormBuilder do |f| %> <%= f.test %> <%= f.submit 'Update' %> <% end %> and then in app/helpers/application_helper.rb module ApplicationHelper class TestFormBuilder < ActionView::Helpers::FormBuilder def test puts 'apa' end end end This, however, gives me an error at the "form_for" uninitialized constant ActionView::Base::CompiledTemplates::TestFormBuilder Where am I doing it wrong?

    Read the article

  • Problem With View Helpers

    - by Richard Knop
    I wrote few custom view helpers but I have a little trouble using them. If I add the helper path in controller action like this: public function fooAction() { $this->view->addHelperPath('My/View/Helper', 'My_View_Helper'); } Then I can use the views from that path without a problem. But when I add the path in the bootstrap file like this: protected function _initView() { $this->view = new Zend_View(); $this->view->doctype('XHTML1_STRICT'); $this->view->headScript()->appendFile($this->view->baseUrl() . '/js/jquery-ui/jquery.js'); $this->view->headMeta()->appendHttpEquiv('Content-Type', 'text/html; charset=UTF-8'); $this->view->headMeta()->appendHttpEquiv('Content-Style-Type', 'text/css'); $this->view->headMeta()->appendHttpEquiv('Content-Language', 'sk'); $this->view->headLink()->appendStylesheet($this->view->baseUrl() . '/css/reset.css'); $this->view->addHelperPath('My/View/Helper', 'My_View_Helper'); } Then the view helpers don't work. Why is that? It's too troublesome to add the path in every controller action. Here is an example of how my custom view helpers look: class My_View_Helper_FooBar { public function fooBar() { return 'hello world'; } } I use them like this in views: <?php echo $this->fooBar(); ?> Should I post my whole bootstrap file? UPDATE: Added complete bootstrap file just in case: class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { protected function _initFrontController() { $this->frontController = Zend_Controller_Front::getInstance(); $this->frontController->addModuleDirectory(APPLICATION_PATH . '/modules'); Zend_Controller_Action_HelperBroker::addPath( 'My/Controller/Action/Helper', 'My_Controller_Action_Helper' ); $this->frontController->registerPlugin(new My_Controller_Plugin_Auth()); $this->frontController->setBaseUrl('/'); } protected function _initView() { $this->view = new Zend_View(); $this->view->doctype('XHTML1_STRICT'); $this->view->headScript()->appendFile($this->view->baseUrl() . '/js/jquery-ui/jquery.js'); $this->view->headMeta()->appendHttpEquiv('Content-Type', 'text/html; charset=UTF-8'); $this->view->headMeta()->appendHttpEquiv('Content-Style-Type', 'text/css'); $this->view->headMeta()->appendHttpEquiv('Content-Language', 'sk'); $this->view->headLink()->appendStylesheet($this->view->baseUrl() . '/css/reset.css'); $this->view->addHelperPath('My/View/Helper', 'My_View_Helper'); } protected function _initDb() { $this->configuration = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENVIRONMENT); $this->dbAdapter = Zend_Db::factory($this->configuration->database); Zend_Db_Table_Abstract::setDefaultAdapter($this->dbAdapter); $stmt = new Zend_Db_Statement_Pdo($this->dbAdapter, "SET NAMES 'utf8'"); $stmt->execute(); } protected function _initAuth() { $this->auth = Zend_Auth::getInstance(); } protected function _initCache() { $frontend= array('lifetime' => 7200, 'automatic_serialization' => true); $backend= array('cache_dir' => 'cache'); $this->cache = Zend_Cache::factory('core', 'File', $frontend, $backend); } public function _initTranslate() { $this->translate = new Zend_Translate('Array', BASE_PATH . '/languages/Slovak.php', 'sk_SK'); $this->translate->setLocale('sk_SK'); } protected function _initRegistry() { $this->registry = Zend_Registry::getInstance(); $this->registry->configuration = $this->configuration; $this->registry->dbAdapter = $this->dbAdapter; $this->registry->auth = $this->auth; $this->registry->cache = $this->cache; $this->registry->Zend_Translate = $this->translate; } protected function _initUnset() { unset($this->frontController, $this->view, $this->configuration, $this->dbAdapter, $this->auth, $this->cache, $this->translate, $this->registry); } protected function _initGetRidOfMagicQuotes() { if (get_magic_quotes_gpc()) { function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } $_POST = array_map('stripslashes_deep', $_POST); $_GET = array_map('stripslashes_deep', $_GET); $_COOKIE = array_map('stripslashes_deep', $_COOKIE); $_REQUEST = array_map('stripslashes_deep', $_REQUEST); } } public function run() { $frontController = Zend_Controller_Front::getInstance(); $frontController->dispatch(); } }

    Read the article

  • Is Spring.Threading.Helpers still supported?

    - by Paul Morrison
    I am converting some old C# code, and it has a CountDownLatch using a package called Spring.Threading.Helpers. The odd thing is that I can't find this package on Google - so a) is it still supported? And, if so, where is it documented? b) What I really want to do is wait for a count to get to zero, but interrupt every so many msecs. Would it just be simpler to set up another thread, and do WaitOnes on an Event specifying an interval? TIA

    Read the article

  • testing helpers with 'haml_tag'

    - by crankharder
    module FooHelper def foo haml_tag(:div) do haml_content("bar") end end end When I test this I get: NoMethodError: undefined method `haml_tag' This code is perfectly valid and works in a development/production environment. It's something to do with having the haml helpers properly loaded in the test environment. Thanks!

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >