Search Results

Search found 182 results on 8 pages for 'htmlhelper'.

Page 5/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • error message: clientside validation

    - by user281180
    What is the meaning of the following error message?How can I use the EnableClienTValidation()? Error 3 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'EnableClientValidation' and no extension method 'EnableClientValidation' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?) c:\Dev\DEV\test3\Code\MvcUI\Views\Customer\Create.aspx 11 13 MvcUI I have reference the following:`" type="text/javascript" <script src="<%=Url.Content("~/Scripts/jquery.validate.js")%>" type="text/javascript"></script> <script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js")%>" type="text/javascript"></script> <script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js")%>" type="text/javascript"></script> <script src="<%= Url.Content("~/Scripts/MicrosoftMvcJQueryValidation.js" )%>" type="text/javascript"></script> `

    Read the article

  • Trouble with ASP.NET MVC auto-scaffolder template

    - by DanM
    I'm trying to write an auto-scaffolder template for Index views. I'd like to be able to pass in a collection of models or view-models (e.g., IQueryable<MyViewModel>) and get back an HTML table that uses the DisplayName attribute for the headings (th elements) and Html.Display(propertyName) for the cells (td elements). Each row should correspond to one item in the collection. Here's what I have so far: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <% var items = (IQueryable<TestProj.ViewModels.TestViewModel>)Model; // How do I make this generic? var properties = items.First().GetMetadata().Properties .Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm)); %> <table> <tr> <% foreach(var property in properties) { %> <th> <%= property.DisplayName %> </th> <% } %> </tr> <% foreach(var item in items) { HtmlHelper itemHtml = ????; // What should I put in place of "????"? %> <tr> <% foreach(var property in properties) { %> <td> <%= itemHtml.Display(property.DisplayName) %> </td> <% } %> </tr> <% } %> </table> Two problems with this: I'd like it to be generic. So, I'd like to replace var items = (IQueryable<TestProj.ViewModels.TestViewModel>)Model; with var items = (IQueryable<T>)Model; or something to that effect. A property Html is automatically created for me when the view is created, but this HtmlHelper applies to the whole collection. I need to somehow create an itemHtml object that applies just to the current item in the foreach loop. I'm not sure how to do this, however, because the constructors for HtmlHelper don't take a Model object. How do I solve these two problems?

    Read the article

  • Why input elements don't render the value passed in ASP.Net MVC?

    - by MediaSlayer
    This post asks this question but doesn't really give an answer, so I thought I would ask the question differently. I have a page that renders a hidden value from the model: <%=Html.Hidden("myName", model.myValue) %> Since I am passing a value in the value parameter, you would think it would output that value, but it doesn't. The code for rendering input fields has the following: string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string)); tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : valueParameter), isExplicitValue); Basically, if the ModelState (which contains posted values) contains a value for the "name" passed, it will use that value instead of your passed value to the helper method. In my case, I updated the model and my updated value wasn't outputted. If I pass a value to a method, I expect that value to be rendered. Am I missing something in this design or is it just wrong?

    Read the article

  • MVC Helper Extension issue

    - by BeCool
    Hi, I need to implement a HtmlHelper extension in my MVC project simply just to output some string but ONLY in the DEBUG mode, not in REALEASE. My first attempt would be: [Conditional("DEBUG")] public static string TestStringForDebugOnly(this HtmlHelper helper, string testString) { return testString; } But obviously that would give a compile error: "The Conditional attribute is not valid because its return type is not void." So my understanding is once you set [Condition] attribute, it doesnt allow to return anything? why? What is other way to implement this kind of function? anyone help would be much appreciated. Thanks!

    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

  • How to Correct & Improve the Design of this Code?

    - by DaveDev
    HI Guys, I've been working on a little experiement to see if I could create a helper method to serialize any of my types to any type of HTML tag I specify. I'm getting a NullReferenceException when _writer = _viewContext.Writer; is called in protected virtual void Dispose(bool disposing) {/*...*/} I think I'm at a point where it almost works (I've gotten other implementations to work) and I was wondering if somebody could point out what I'm doing wrong? Also, I'd be interested in hearing suggestions on how I could improve the design? So basically, I have this code that will generate a Select box with a number of options: // the idea is I can use one method to create any complete tag of any type // and put whatever I want in the content area <% using (Html.GenerateTag<SelectTag>(Model, new { href = Url.Action("ActionName") })) { %> <%foreach (var fund in Model.Funds) {%> <% using (Html.GenerateTag<OptionTag>(fund)) { %> <%= fund.Name %> <% } %> <% } %> <% } %> This Html.GenerateTag helper is defined as: public static MMTag GenerateTag<T>(this HtmlHelper htmlHelper, object elementData, object attributes) where T : MMTag { return (T)Activator.CreateInstance(typeof(T), htmlHelper.ViewContext, elementData, attributes); } Depending on the type of T it'll create one of the types defined below, public class HtmlTypeBase : MMTag { public HtmlTypeBase() { } public HtmlTypeBase(ViewContext viewContext, params object[] elementData) { base._viewContext = viewContext; base.MergeDataToTag(viewContext, elementData); } } public class SelectTag : HtmlTypeBase { public SelectTag(ViewContext viewContext, params object[] elementData) { base._tag = new TagBuilder("select"); //base.MergeDataToTag(viewContext, elementData); } } public class OptionTag : HtmlTypeBase { public OptionTag(ViewContext viewContext, params object[] elementData) { base._tag = new TagBuilder("option"); //base.MergeDataToTag(viewContext, _elementData); } } public class AnchorTag : HtmlTypeBase { public AnchorTag(ViewContext viewContext, params object[] elementData) { base._tag = new TagBuilder("a"); //base.MergeDataToTag(viewContext, elementData); } } all of these types (anchor, select, option) inherit from HtmlTypeBase, which is intended to perform base.MergeDataToTag(viewContext, elementData);. This doesn't happen though. It works if I uncomment the MergeDataToTag methods in the derived classes, but I don't want to repeat that same code for every derived class I create. This is the definition for MMTag: public class MMTag : IDisposable { internal bool _disposed; internal ViewContext _viewContext; internal TextWriter _writer; internal TagBuilder _tag; internal object[] _elementData; public MMTag() {} public MMTag(ViewContext viewContext, params object[] elementData) { } public void Dispose() { Dispose(true /* disposing */); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { _disposed = true; _writer = _viewContext.Writer; _writer.Write(_tag.ToString(TagRenderMode.EndTag)); } } protected void MergeDataToTag(ViewContext viewContext, object[] elementData) { Type elementDataType = elementData[0].GetType(); foreach (PropertyInfo prop in elementDataType.GetProperties()) { if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(Decimal) || prop.PropertyType == typeof(String)) { object propValue = prop.GetValue(elementData[0], null); string stringValue = propValue != null ? propValue.ToString() : String.Empty; _tag.Attributes.Add(prop.Name, stringValue); } } var dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); var attributes = elementData[1]; if (attributes != null) { foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(attributes)) { object value = descriptor.GetValue(attributes); dic.Add(descriptor.Name, value); } } _tag.MergeAttributes<string, object>(dic); _viewContext = viewContext; _viewContext.Writer.Write(_tag.ToString(TagRenderMode.StartTag)); } } Thanks Dave

    Read the article

  • Anti-Forgery Request Recipes For ASP.NET MVC And 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, the work would be 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 ValidateAntiForgeryTokenWrapperAttribute 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. Specify Non-constant salt in runtime By default, the salt should be a compile time constant, so it can be used for the [ValidateAntiForgeryToken] or [ValidateAntiForgeryTokenWrapper] attribute. Problem One Web product might be sold to many clients. If a constant salt is evaluated in compile time, after the product is built and deployed to many clients, they all have the same salt. Of course, clients do not like this. Even some clients might want to specify a custom salt in configuration. In these scenarios, salt is required to be a runtime value. Solution In the above [ValidateAntiForgeryToken] and [ValidateAntiForgeryTokenWrapper] attribute, the salt is passed through constructor. So one solution is to remove this parameter:public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = AntiForgeryToken.Value }; } // Other members. } But here the injected dependency becomes a hard dependency. So the other solution is moving validation code into controller to work around the limitation of attributes:public abstract class AntiForgeryControllerBase : Controller { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; protected AntiForgeryControllerBase(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } protected override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } Then make controller classes inheriting from this AntiForgeryControllerBase class. Now the salt is no long required to be a compile time constant. Submit token via AJAX For browser side, once server side turns on anti-forgery validation for HTTP POST, all AJAX POST requests will fail by default. Problem In AJAX scenarios, the HTTP POST request is not sent by form. Take jQuery as an example:$.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 Basically, the tokens must be printed to browser then sent back to server. So first of all, HtmlHelper.AntiForgeryToken() need to be called somewhere. Now the browser has token in both 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, where $.appendAntiForgeryToken() is useful: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 an iframe, while the token is in the parent window. Here, token's container 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

  • How to fix security exception when using recaptcha on MVC site

    - by camainc
    I followed this excellent blog post to implement recaptcha on my MVC site: http://devlicio.us/blogs/derik_whittaker/archive/2008/12/02/using-recaptcha-with-asp-net-mvc.aspx I converted the code to VB, and everything seems to compile ok. However, when the code gets to the place where the recapture is about to be generated, I get a security exception. Here is the function where the exception occurs (on the last line in the function): <Extension()> _ Public Function GenerateCaptcha(ByVal htmlHelper As HtmlHelper) As MvcHtmlString Dim captchaControl As New Recaptcha.RecaptchaControl With captchaControl .ID = "recaptcha" .Theme = "blackglass" .PublicKey = "6Lcv9AsAAAAAALCSZNRfWFmrKjw2AR-yuZAL84Bd" .PrivateKey = "6Lcv9AsAAAAAAHCbRujWcZzrY0z6G_HIMvFyYEPR" End With Dim htmlWriter As New HtmlTextWriter(New IO.StringWriter) captchaControl.RenderControl(htmlWriter) Return MvcHtmlString.Create(htmlWriter.InnerWriter.ToString()) End Function The exception is this: Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. Has anyone else seen this exception, and if so, how did you fix it? Thanks

    Read the article

  • How can I render a list of objects using DisplayFor but from the controller in ASP.NET MVC?

    - by Darragh
    Here's the scenaio, I have an Employee object and a Company object which has a list of employees. I have Company.aspx which inherits from ViewPage<Company>. In Company.aspx I call Html.DisplayFor(m => m.Employees). I have an Employee.ascx partial view which inherits from ViewUserControl<Employee in my DisplayTemplates folder. Everything works fine and Company.aspx renders the Employee.ascx partial for each employee. Now I have two additional methods on my controller called GetEmployees and GetEmployee(Id). In the GetEmployee(Id) action I want to return the markup to display this one employee, and in GetEmployees() I want to render the markup to display all the employees (these two action methods will be called via AJAX). In the GetEmployee action I call return PartialView("DisplayTemplates\Employee", employee) This works, although I'd prefer something like return PartialViewFor(employee) which would determine the view name by convention. Anwyay, my question is how should I implement the GetEmployees() action? I don't want to create any more views, because frankly, I don't see why I should have to. I've tried the following which fails miserably :) return Content(New HtmlHelper<IList<Of DebtDto>>(null, null).DisplayFor(m => debts)); However if I could create an instance of an HtmlHelper object in my controller, I suppose I could get it to work, but it feels wrong. Any ideas? Have i missed something obvious?

    Read the article

  • CSRF Protection in AJAX Requests using MVC2

    - by mnemosyn
    The page I'm building depends heavily on AJAX. Basically, there is just one "page" and every data transfer is handled via AJAX. Since overoptimistic caching on the browser side leads to strange problems (data not reloaded), I have to perform all requests (also reads) using POST - that forces a reload. Now I want to prevent the page against CSRF. With form submission, using Html.AntiForgeryToken() works neatly, but in AJAX-request, I guess I will have to append the token manually? Is there anything out-of-the box available? My current attempt looks like this: I'd love to reuse the existing magic. However, HtmlHelper.GetAntiForgeryTokenAndSetCookie is private and I don't want to hack around in MVC. The other option is to write an extension like public static string PlainAntiForgeryToken(this HtmlHelper helper) { // extract the actual field value from the hidden input return helper.AntiForgeryToken().DoSomeHackyStringActions(); } which is somewhat hacky and leaves the bigger problem unsolved: How to verify that token? The default verification implementation is internal and hard-coded against using form fields. I tried to write a slightly modified ValidateAntiForgeryTokenAttribute, but it uses an AntiForgeryDataSerializer which is private and I really didn't want to copy that, too. At this point it seems to be easier to come up with a homegrown solution, but that is really duplicate code. Any suggestions how to do this the smart way? Am I missing something completely obvious?

    Read the article

  • Custom Html Helper is not working in asp.net MVC 2.0

    - by chobo2
    Hey I was using this custom html helper in asp.net mvc 1.0 but now I am trying to use it in a 2.0 project and it crashes http://blog.pagedesigners.co.nz/archive/2009/07/15/asp.net-mvc-ndash-validation-summary-with-2-forms-amp-1.aspx This is the error I get. System.MissingMethodException was unhandled by user code Message=Method not found: 'System.String System.Web.Mvc.Html.ValidationExtensions.ValidationSummary(System.Web.Mvc.HtmlHelper)'. Source=CustomHtmlHelpers StackTrace: at CustomHtmlHelpers.ActionValidationSummaryHelper.ActionValidationSummary(HtmlHelper html, String action) at ASP.views_signin_signin_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer) in SignIn.aspx:line 23 at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) at System.Web.UI.Control.Render(HtmlTextWriter writer) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer) at ASP.views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer) Site.Master:line 64 at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) at System.Web.UI.Control.Render(HtmlTextWriter writer) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer) at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) at System.Web.UI.Page.Render(HtmlTextWriter writer) at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException: My other html helpers in the same library do work. I added the namespace into the webconfig.

    Read the article

  • Populating dropdownlist in asp.net mvc doesn't seem to work for me...

    - by Pandiya Chendur
    I use a dropdownlist in one of my create.aspx but it some how doesnt seem to work... public IEnumerable<Materials> FindAllMeasurements() { var mesurements = from mt in db.MeasurementTypes select new Materials() { Id= Convert.ToInt64(mt.Id), Mes_Name= mt.Name }; return mesurements; } and my controller, public ActionResult Create() { var mesurementTypes = consRepository.FindAllMeasurements().AsEnumerable(); ViewData["MeasurementType"] = new SelectList(mesurementTypes, "Id", "Mes_Name"); return View(); } and my create.aspx has this, <p> <label for="MeasurementTypeId">MeasurementType:</label> <%= Html.DropDownList("MeasurementType", ViewData["MeasurementType"])%> <%= Html.ValidationMessage("MeasurementTypeId", "*") %> </p> When i execute this i got these errors, System.Web.Mvc.HtmlHelper<CrMVC.Models.Material>' does not contain a definition for 'DropDownList' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' has some invalid arguments 2.cannot convert from 'object' to 'System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>

    Read the article

  • Cake Php After Php GD library installation comes error as appending 'index.php' in urls

    - by Jusnit
    I am using using Cake PHP with nginx server, inorder to enable captcha support , I installed the PHP GD library to server After the installation , All the urls in cake php is appended with 'index.php' Like www.mydomain.com/index.php instead of www.mydomain.com There cake php HtmlHelper link and image function, it all appending url "/index.php/img/flower.jpg" instead "/img/flower.jpg". Please help to solve this problem..

    Read the article

  • WPF more dynamic views and DataAnnotations

    - by Ingó Vals
    Comparing WPF and Asp.Net Razor/HtmlHelper I find WPF/Xaml to be somewhat lacking in creating views. With HtmlHelpers you could define in one place how you wan't to represent specific type of data and include elements set from the DataAnnotations of the property. In WPF you can also define DataTemplates for data but it seems much more limited then EditorTemplates. It doesn't use information from DataAnnotations. Also the layout of elements can be bothersome. I hate having to constantly add RowDefinitions and update the Grid.Row attribute of lot of elements when I add a new property somewhere in line. I understand that GUI programming can be a lot of grunt work like this but as Asp.Net MVC has shown there are ways around that. What solutions are out there to make view creation in WPF a little bit cleaner, maintainable and more dynamic?

    Read the article

  • ASP.NET MVC 2 InputExtensions different on server than local machine

    - by Mike
    Hi everyone, So this is kind of a crazy problem to me, but I've had no luck Googling it. I have an ASP.NET MVC 2 application (under .NET 4.0) running locally just fine. When I upload it to my production server (under shared hosting) I get Compiler Error Message: CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TextBoxFor' and no extension method 'TextBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?) for this code: <%= this.Html.TextBoxFor(person => person.LastName) %> This is one of the new standard extension methods in MVC 2. So I wrote some diagnostic code: System.Reflection.Assembly ass = System.Reflection.Assembly.GetAssembly(typeof(InputExtensions)); Response.Write("From GAC: " + ass.GlobalAssemblyCache.ToString() + "<br/>"); Response.Write("ImageRuntimeVersion: " + ass.ImageRuntimeVersion.ToString() + "<br/>"); Response.Write("Version: " + System.Diagnostics.FileVersionInfo.GetVersionInfo(ass.Location).ToString() + "<br/>"); foreach (var method in typeof(InputExtensions).GetMethods()) { Response.Write(method.Name + "<br/>"); } running locally (where it works fine), I get this as output: From GAC: True ImageRuntimeVersion: v2.0.50727 Version: File: C:\Windows\assembly\GAC_MSIL\System.Web.Mvc\2.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll InternalName: System.Web.Mvc.dll OriginalFilename: System.Web.Mvc.dll FileVersion: 2.0.50217.0 FileDescription: System.Web.Mvc.dll Product: Microsoft® .NET Framework ProductVersion: 2.0.50217.0 Debug: False Patched: False PreRelease: False PrivateBuild: False SpecialBuild: False Language: Language Neutral CheckBox CheckBox CheckBox CheckBox CheckBox CheckBox CheckBoxFor CheckBoxFor CheckBoxFor Hidden Hidden Hidden Hidden HiddenFor HiddenFor HiddenFor Password Password Password Password PasswordFor PasswordFor PasswordFor RadioButton RadioButton RadioButton RadioButton RadioButton RadioButton RadioButtonFor RadioButtonFor RadioButtonFor TextBox TextBox TextBox TextBox TextBoxFor TextBoxFor TextBoxFor ToString Equals GetHashCode GetType and when running on the production server (where it fails), I see: From GAC: True ImageRuntimeVersion: v2.0.50727 Version: File: C:\Windows\assembly\GAC_MSIL\System.Web.Mvc\2.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll InternalName: System.Web.Mvc.dll OriginalFilename: System.Web.Mvc.dll FileVersion: 2.0.41001.0 FileDescription: System.Web.Mvc.dll Product: Microsoft® .NET Framework ProductVersion: 2.0.41001.0 Debug: False Patched: False PreRelease: False PrivateBuild: False SpecialBuild: False Language: Language Neutral CheckBox CheckBox CheckBox CheckBox CheckBox CheckBox Hidden Hidden Hidden Hidden Hidden Hidden Password Password Password Password RadioButton RadioButton RadioButton RadioButton RadioButton RadioButton TextBox TextBox TextBox TextBox ToString Equals GetHashCode GetType note that "TextBoxFor" is not present (hence the error). I have MVC referenced in the csproj: <Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <SpecificVersion>True</SpecificVersion> <HintPath>References\System.Web.Mvc.dll</HintPath> <Private>True</Private> </Reference> I just can't figure it what to do next. Thoughts? Thanks! -Mike

    Read the article

  • Breadcrumbs in CakePHP

    - by kicaj
    I use HtmlHelper from CakePHP to create breadcrumbs navigation for my page... And i set $html->getCrumbs('separator', 'Home Page') to default.ctp and in other views i set $html->addCrumbs('nameLink', 'linkUrl'); All works fine! But when I open my Home Page there is no breadcrumbs, why?

    Read the article

  • asp.net mvc deployment

    - by tomasz
    Ive managed to get asp.net mvc up and running on an iis6 server, but I keep getting silly messages like 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'RenderPartial' I've got all the required dlls and even installed mvc from http://www.microsoft.com/downloads/details.aspx?FamilyID=c9ba1fe1-3ba8-439a-9e21-def90a8615a9&displaylang=en any clues about what Im missing? Cheers

    Read the article

  • How do I solve an AntiForgeryToken exception that occurs after an iisreset in my ASP.Net MVC app?

    - by Colin Newell
    I’m having problems with the AntiForgeryToken in ASP.Net MVC. If I do an iisreset on my web server and a user continues with their session they get bounced to a login page. Not terrible but then the AntiForgery token blows up and the only way to get going again is to blow away the cookie on the browser. With the beta version of version 1 it used to go wrong when reading the cookie back in for me so I used to scrub it before asking for a validation token but that was fixed when it was released. For now I think I’ll roll back to my code that fixed the beta problem but I can’t help but think I’m missing something. Is there a simpler solution, heck should I just drop their helper and create a new one from scratch? I get the feeling that a lot of the problem is the fact that it’s tied so deeply into the old ASP.Net pipeline and is trying to kludge it into doing something it wasn’t really designed to do. I had a look in the source code for the ASP.Net MVC 2 RC and it doesn't look like the code has changed much so while I haven't tried it, I don't think there are any answers there. Here is the relevant part of the stack trace of the exception. Edit: I just realised I didn't mention that this is just trying to insert the token on the GET request. This isn't the validation that occurs when you do a POST kicking off. System.Web.Mvc.HttpAntiForgeryException: A required anti-forgery token was not supplied or was invalid. ---> System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. ---> System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 127.0.0.1 Port: 4991 User-Agent: scrubbed ViewState: scrubbed Referer: blah Path: /oursite/Account/Login ---> System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed. at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) --- End of inner exception stack trace --- --- End of inner exception stack trace --- at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken) --- End of inner exception stack trace --- at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken) at System.Web.Mvc.HtmlHelper.GetAntiForgeryTokenAndSetCookie(String salt, String domain, String path) at System.Web.Mvc.HtmlHelper.AntiForgeryToken(String salt, String domain, String path)

    Read the article

  • Watermark TextBox in ASP.NET MVC

    - by adrin
    What is the easiest way to implement watermark textbox control in ASP.NET MVC, are there any such controls on the internet (codeplex maybe). I suppose it is quite simple to write one extending HtmlHelper and using jquery watermark textbox implementation.

    Read the article

  • How do I create a strongly typed BeginForm?

    - by itchi
    I've seen a few examples of people using this syntax for HTML.BeginForm: (Html.BeginForm<Type>(action => action.ActionName(id))) But when I try this syntax all I get is a: The non-generic method System.Web.Mvc.Html.FormExtensions.BeginForm(System.Web.Mvc.HtmlHelper)' cannot be used with type arguments What am I missing?

    Read the article

  • mvc create my own html helper, how can i access httpcontext?

    - by rj
    Hi, I've come across two recommendations for creating custom html helpers: either extend an existing one, or write your own class. I'd prefer to keep my custom code separated, it seems a bit sloppy to extend helpers for a decent-size application. But the benefit I see in extending is that 'This HtmlHelper helper' is passed as a parameter, through which I can get ViewContext.HtmlContext. My question is, how can I roll my own helper class and still have ViewContext.HtmlContext available to me? Thanks!

    Read the article

  • What Patterns Should I Consider For a Html Widget Generator?

    - by DaveDev
    I'm looking to see if I can design a HtmlHelper extension method that will generate the Html for different types of widgets I want to produce. Each different type of widget implements functionality to get and prepare any data it needs to render. Can anyone suggest any patterns I could refer to for approaches to take? I know there are probably frameworks available that will do this for me, but I thought I'd give it a try anyway. Any points of advice? Thanks

    Read the article

  • HtmlHelperExtensions are not visible in view mvc3 asp.net

    - by user1299372
    I've added a class for the HTML Custom Extensions: using System; using System.Linq.Expressions; using System.Text; using System.Web.Mvc; using System.Web.Mvc.Html; namespace App.MvcHtmlHelpers { public static class HtmlHelperExtensions { public static MvcHtmlString ComboBox(HtmlHelper html, string name, SelectList items, string selectedValue) { var sb = new StringBuilder(); sb.Append(html.DropDownList(name + "_hidden", items, new { @style = "width: 200px;", @onchange = "$('input#" + name + "').val($(this).val());" })); sb.Append(html.TextBox(name, selectedValue, new { @style = "margin-left: -199px; width: 179px; height: 1.2em; border: 0;" })); return MvcHtmlString.Create(sb.ToString()); } public static MvcHtmlString ComboBoxFor<TModel, TProperty>(HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, SelectList items) { var me = (MemberExpression)expression.Body; var name = me.Member.Name; var sb = new StringBuilder(); sb.Append(html.DropDownList(name + "_hidden", items, new { @style = "width: 200px;", @onchange = "$('input#" + name + "').val($(this).val());" })); sb.Append(html.TextBoxFor(expression, new { @style = "margin-left: -199px; width: 179px; height: 1.2em; border: 0;" })); return MvcHtmlString.Create(sb.ToString()); } I've also registered it in my site web config: <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> <add namespace="App.MvcHtmlHelpers"/> </namespaces> In my view, I import the namespace: <%@ Import Namespace="RSPWebApp.MvcHtmlHelpers" %> But when I go to call it in the view, it doesn't recognize the custom extension. Can someone help me by telling me what I might have missed? Thanks so much in advance! <%:Html.ComboBoxFor(a => a.Street2, streetAddressListItems) %

    Read the article

  • ASP.NET MVC–How to show asterisk after required field label

    - by DigiMortal
    Usually we have some required fields on our forms and it would be nice if ASP.NET MVC views can detect those fields automatically and display nice red asterisk after field label. As this functionality is not built in I built my own solution based on data annotations. In this posting I will show you how to show red asterisk after label of required fields. Here are the main information sources I used when working out my own solution: How can I modify LabelFor to display an asterisk on required fields? (stackoverflow) ASP.NET MVC – Display visual hints for the required fields in your model (Radu Enuca) Although my code was first written for completely different situation I needed it later and I modified it to work with models that use data annotations. If data member of model has Required attribute set then asterisk is rendered after field. If Required attribute is missing then there will be no asterisk. Here’s my code. You can take just LabelForRequired() methods and paste them to your own HTML extension class. public static class HtmlExtensions {     [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]     public static MvcHtmlString LabelForRequired<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText = "")     {         return LabelHelper(html,             ModelMetadata.FromLambdaExpression(expression, html.ViewData),             ExpressionHelper.GetExpressionText(expression), labelText);     }       private static MvcHtmlString LabelHelper(HtmlHelper html,         ModelMetadata metadata, string htmlFieldName, string labelText)     {         if (string.IsNullOrEmpty(labelText))         {             labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();         }           if (string.IsNullOrEmpty(labelText))         {             return MvcHtmlString.Empty;         }           bool isRequired = false;           if (metadata.ContainerType != null)         {             isRequired = metadata.ContainerType.GetProperty(metadata.PropertyName)                             .GetCustomAttributes(typeof(RequiredAttribute), false)                             .Length == 1;         }           TagBuilder tag = new TagBuilder("label");         tag.Attributes.Add(             "for",             TagBuilder.CreateSanitizedId(                 html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)             )         );           if (isRequired)             tag.Attributes.Add("class", "label-required");           tag.SetInnerText(labelText);           var output = tag.ToString(TagRenderMode.Normal);             if (isRequired)         {             var asteriskTag = new TagBuilder("span");             asteriskTag.Attributes.Add("class", "required");             asteriskTag.SetInnerText("*");             output += asteriskTag.ToString(TagRenderMode.Normal);         }         return MvcHtmlString.Create(output);     } } And here’s how to use LabelForRequired extension method in your view: <div class="field">     @Html.LabelForRequired(m => m.Name)     @Html.TextBoxFor(m => m.Name)     @Html.ValidationMessageFor(m => m.Name) </div> After playing with CSS style called .required my example form looks like this: These red asterisks are not part of original view mark-up. LabelForRequired method detected that these properties have Required attribute set and rendered out asterisks after field names. NB! By default asterisks are not red. You have to define CSS class called “required” to modify how asterisk looks like and how it is positioned.

    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

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >