Search Results

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

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

  • .net mvc2 custom HtmlHelper extension unit testing

    - by alex
    My goal is to be able to unit test some custom HtmlHelper extensions - which use RenderPartial internally. http://ox.no/posts/mocking-htmlhelper-in-asp-net-mvc-2-and-3-using-moq I've tried using the method above to mock the HtmlHelper. However, I'm running into Null value exceptions. "Parameter name: view" Anyone have any idea?? Thanks. Below are the ideas of the code: [TestMethod] public void TestMethod1() { var helper = CreateHtmlHelper(new ViewDataDictionary()); helper.RenderPartial("Test"); // supposingly this line is within a method to be tested Assert.AreEqual("test", helper.ViewContext.Writer.ToString()); } public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd) { Mock<ViewContext> mockViewContext = new Mock<ViewContext>( new ControllerContext( new Mock<HttpContextBase>().Object, new RouteData(), new Mock<ControllerBase>().Object), new Mock<IView>().Object, vd, new TempDataDictionary(), new StringWriter()); var mockViewDataContainer = new Mock<IViewDataContainer>(); mockViewDataContainer.Setup(v => v.ViewData) .Returns(vd); return new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object); }

    Read the article

  • How to Unit Test HtmlHelper similar to using(Html.BeginForm()){ }

    - by DaveDev
    Can somebody please suggest how I could write a Unit Test with Moq for following HtmlHelper method? public static HtmlTagBase GenerateTag<T>(this HtmlHelper htmlHelper , object elementData , object attributes) where T : HtmlTagBase { return (T)Activator.CreateInstance(typeof(T) , htmlHelper.ViewContext , elementData , attributes); } which you would use as follows (please note the using statement - this is causing me confusion): <%--Model is a type of ShareClass--%> <% using (Html.GenerateTag<DivTag>(Model)) { %> My Div <% } %> using this method, if you specify T as type DivTag, where ShareClass is defined as public class ShareClass { public string Name { get; set; } public string Type { get; set; } public IEnumerable<Fund> Funds { get; set; } public ShareClass(string name, string shareClassType) { this.Name = name; this.Type = shareClassType; } } the following html will be rendered: <div class="ShareClass" shareclass-type="ShareClass_A" shareclass-name="MyShareClass">My Div</div>

    Read the article

  • ASP.Net MVC view unable to see HtmlHelper extension method

    - by larryq
    Hi everyone, We're going through an ASP.Net MVC book and are having trouble with using an extenstion method within our view. The Extension method looks like this: using System; using System.Runtime.CompilerServices; using System.Web.Mvc; namespace MvcBookApplication { public static class HtmlHelperExtensions { public static string JQueryGenerator(this HtmlHelper htmlHelper, string formName, object model); } } We use the extension method in our view like this: <%=Html.JQueryGenerator("createmessage", ViewData.Model)%> The problem is, that line of code says JQueryGenerator isn't a recognized method of HtmlHelper. I believe we've got the correct references set in the web project, but are there other things we can check? There's no using statement for views, is there?

    Read the article

  • HtmlHelper Getting the route name

    - by Simon G
    Hi, I've created a html helper that adds a css class property to a li item if the user is on the current page. The helper looks like this: public static string MenuItem( this HtmlHelper helper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes ) { string currentControllerName = ( string )helper.ViewContext.RouteData.Values["controller"]; string currentActionName = ( string )helper.ViewContext.RouteData.Values["action"]; var builder = new TagBuilder( "li" ); // Add selected class if ( currentControllerName.Equals( controllerName, StringComparison.CurrentCultureIgnoreCase ) && currentActionName.Equals( actionName, StringComparison.CurrentCultureIgnoreCase ) ) builder.AddCssClass( "active" ); // Add link builder.InnerHtml = helper.ActionLink( linkText, actionName, controllerName, routeValues, htmlAttributes ); // Render Tag Builder return builder.ToString( TagRenderMode.Normal ); } I want to expand this class so I can pass a route name to the helper and if the user is on that route then it adds the css class to the li item. However I'm having difficulty finding the route the user is on. Is this possible? The code I have so far is: public static string MenuItem( this HtmlHelper helper, string linkText, string routeName, object routeValues, object htmlAttributes ) { string currentControllerName = ( string )helper.ViewContext.RouteData.Values["controller"]; string currentActionName = ( string )helper.ViewContext.RouteData.Values["action"]; var builder = new TagBuilder( "li" ); // Add selected class // Some code for here // if ( routeName == currentRoute ) AddCssClass; // Add link builder.InnerHtml = helper.RouteLink( linkText, routeName, routeValues, htmlAttributes ); // Render Tag Builder return builder.ToString( TagRenderMode.Normal ); } BTW I'm using MVC 1.0. Thanks

    Read the article

  • ASP.NET MVC: null reference exception using HtmlHelper.TextBox and custom model binder

    - by mr.nicksta
    I have written a class which implements IModelBinder (see below). This class handles a form which has 3 inputs each representing parts of a date value (day, month, year). I have also written a corresponding HtmlHelper extension method to print out three fields on the form. When the day, month, year inputs are given values which can be parsed, but a seperate value fails validation, all is fine - the fields are repopulated and the page served to the user as expected. however when an invalid values are supplied and a DateTime cannot be parsed, i return an arbitrary DateTime so that the fields will be repopulated when returned to the user. I read up on similar problems people have had and they all seemed to be due to lack of calling SetModelValue(). I wasn't doing this, but even after adding the problem has not been resolved. public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { string modelName = bindingContext.ModelName; string monthKey = modelName + ".Month"; string dayKey = modelName + ".Day"; string yearKey = modelName + ".Year"; //get values submitted on form string year = bindingContext.ValueProvider[yearKey].AttemptedValue; string month = bindingContext.ValueProvider[monthKey].AttemptedValue; string day = bindingContext.ValueProvider[dayKey].AttemptedValue; DateTime parsedDate; if (DateTime.TryParse(string.Format(DateFormat, year, month, day), out parsedDate)) return parsedDate; //could not parse date time report error, return current date bindingContext.ModelState.AddModelError(yearKey, ValidationErrorMessages.DateInvalid); //added this after reading similar problems, does not fix! bindingContext.ModelState.SetModelValue(modelName, bindingContext.ValueProvider[modelName]); return DateTime.Today; } the null reference exception is thrown when i attempt to create a textbox for the Year property of the date, but strangely not for Day or Month! Can anyone offer an explanation as to why this is? Thanks :-)

    Read the article

  • How to Unit Test HtmlHelper with Moq?

    - by DaveDev
    Could somebody show me how you would go about creating a mock HTML Helper with Moq? This article has a link to an article claiming to describe this, but following the link only returns an ASP.NET Runtime Error [edit] I asked a more specific question related to the same subject here, but it hasn't gotten any responses. I figured it was too specific, so I thought I could get a more general answer to a more general question and modify it to meet my requirements. Thanks

    Read the article

  • Persisting model state in ASP.NET MVC using Serialize HTMLHelper

    - by shiju
    ASP.NET MVC 2 futures assembly provides a HTML helper method Serialize that can be use for persisting your model object. The Serialize  helper method will serialize the model object and will persist it in a hidden field in the HTML form. The Serialize  helper is very useful when situations like you are making multi-step wizard where a single model class is using for all steps in the wizard. For each step you want to retain the model object's whole state.The below is serializing our model object. The model object should be a Serializable class in order to work with Serialize helper method. <% using (Html.BeginForm("Register","User")) {%><%= Html.Serialize("User",Model) %> This will generate hidden field with name "user" and the value will the serialized format of our model object.In the controller action, you can place the DeserializeAttribute in the action method parameter. [HttpPost]               public ActionResult Register([DeserializeAttribute] User user, FormCollection userForm) {     TryUpdateModel(user, userForm.ToValueProvider());     //To Do } In the above action method you will get the same model object that you serialized in your view template. We are updating the User model object with the form field values.

    Read the article

  • Persisting model state in ASP.NET MVC using Serialize HTMLHelper

    - by shiju
    ASP.NET MVC 2 futures assembly provides a HTML helper method Serialize that can be use for persisting your model object. The Serialize  helper method will serialize the model object and will persist it in a hidden field in the HTML form. The Serialize  helper is very useful when situations like you are making multi-step wizard where a single model class is using for all steps in the wizard. For each step you want to retain the model object's whole state.The below is serializing our model object. The model object should be a Serializable class in order to work with Serialize helper method. <% using (Html.BeginForm("Register","User")) {%><%= Html.Serialize("User",Model) %> This will generate hidden field with name "user" and the value will the serialized format of our model object.In the controller action, you can place the DeserializeAttribute in the action method parameter. [HttpPost]               public ActionResult Register([DeserializeAttribute] User user, FormCollection userForm) {     TryUpdateModel(user, userForm.ToValueProvider());     //To Do } In the above action method you will get the same model object that you serialized in your view template. We are updating the User model object with the form field values.

    Read the article

  • ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes

    - by Rick Strahl
    So here's a binding behavior in ASP.NET MVC that I didn't really get until today: HtmlHelpers controls (like .TextBoxFor() etc.) don't bind to model values on Postback, but rather get their value directly out of the POST buffer from ModelState. Effectively it looks like you can't change the display value of a control via model value updates on a Postback operation. To demonstrate here's an example. I have a small section in a document where I display an editable email address: This is what the form displays on a GET operation and as expected I get the email value displayed in both the textbox and plain value display below, which reflects the value in the mode. I added a plain text value to demonstrate the model value compared to what's rendered in the textbox. The relevant markup is the email address which needs to be manipulated via the model in the Controller code. Here's the Razor markup: <div class="fieldcontainer"> <label> Email: &nbsp; <small>(username and <a href="http://gravatar.com">Gravatar</a> image)</small> </label> <div> @Html.TextBoxFor( mod=> mod.User.Email, new {type="email",@class="inputfield"}) @Model.User.Email </div> </div>   So, I have this form and the user can change their email address. On postback the Post controller code then asks the business layer whether the change is allowed. If it's not I want to reset the email address back to the old value which exists in the database and was previously store. The obvious thing to do would be to modify the model. Here's the Controller logic block that deals with that:// did user change email? if (!string.IsNullOrEmpty(oldEmail) && user.Email != oldEmail) { if (userBus.DoesEmailExist(user.Email)) { userBus.ValidationErrors.Add("New email address exists already. Please…"); user.Email = oldEmail; } else // allow email change but require verification by forcing a login user.IsVerified = false; }… model.user = user; return View(model); The logic is straight forward - if the new email address is not valid because it already exists I don't want to display the new email address the user entered, but rather the old one. To do this I change the value on the model which effectively does this:model.user.Email = oldEmail; return View(model); So when I press the Save button after entering in my new email address ([email protected]) here's what comes back in the rendered view: Notice that the textbox value and the raw displayed model value are different. The TextBox displays the POST value, the raw value displays the actual model value which are different. This means that MVC renders the textbox value from the POST data rather than from the view data when an Http POST is active. Now I don't know about you but this is not the behavior I expected - initially. This behavior effectively means that I cannot modify the contents of the textbox from the Controller code if using HtmlHelpers for binding. Updating the model for display purposes in a POST has in effect - no effect. (Apr. 25, 2012 - edited the post heavily based on comments and more experimentation) What should the behavior be? After getting quite a few comments on this post I quickly realized that the behavior I described above is actually the behavior you'd want in 99% of the binding scenarios. You do want to get the POST values back into your input controls at all times, so that the data displayed on a form for the user matches what they typed. So if an error occurs, the error doesn't mysteriously disappear getting replaced either with a default value or some value that you changed on the model on your own. Makes sense. Still it is a little non-obvious because the way you create the UI elements with MVC, it certainly looks like your are binding to the model value:@Html.TextBoxFor( mod=> mod.User.Email, new {type="email",@class="inputfield",required="required" }) and so unless one understands a little bit about how the model binder works this is easy to trip up. At least it was for me. Even though I'm telling the control which model value to bind to, that model value is only used initially on GET operations. After that ModelState/POST values provide the display value. Workarounds The default behavior should be fine for 99% of binding scenarios. But if you do need fix up values based on your model rather than the default POST values, there are a number of ways that you can work around this. Initially when I ran into this, I couldn't figure out how to set the value using code and so the simplest solution to me was simply to not use the MVC Html Helper for the specific control and explicitly bind the model via HTML markup and @Razor expression: <input type="text" name="User.Email" id="User_Email" value="@Model.User.Email" /> And this produces the right result. This is easy enough to create, but feels a little out of place when using the @Html helpers for everything else. As you can see by the difference in the name and id values, you also are forced to remember the naming conventions that MVC imposes in order for ModelBinding to work properly which is a pain to remember and set manually (name is the same as the property with . syntax, id replaces dots with underlines). Use the ModelState Some of my original confusion came because I didn't understand how the model binder works. The model binder basically maintains ModelState on a postback, which holds a value and binding errors for each of the Post back value submitted on the page that can be mapped to the model. In other words there's one ModelState entry for each bound property of the model. Each ModelState entry contains a value property that holds AttemptedValue and RawValue properties. The AttemptedValue is essentially the POST value retrieved from the form. The RawValue is the value that the model holds. When MVC binds controls like @Html.TextBoxFor() or @Html.TextBox(), it always binds values on a GET operation. On a POST operation however, it'll always used the AttemptedValue to display the control. MVC binds using the ModelState on a POST operation, not the model's value. So, if you want the behavior that I was expecting originally you can actually get it by clearing the ModelState in the controller code:ModelState.Clear(); This clears out all the captured ModelState values, and effectively binds to the model. Note this will produce very similar results - in fact if there are no binding errors you see exactly the same behavior as if binding from ModelState, because the model has been updated from the ModelState already and binding to the updated values most likely produces the same values you would get with POST back values. The big difference though is that any values that couldn't bind - like say putting a string into a numeric field - will now not display back the value the user typed, but the default field value or whatever you changed the model value to. This is the behavior I was actually expecting previously. But - clearing out all values might be a bit heavy handed. You might want to fix up one or two values in a model but rarely would you want the entire model to update from the model. So, you can also clear out individual values on an as needed basis:if (userBus.DoesEmailExist(user.Email)) { userBus.ValidationErrors.Add("New email address exists already. Please…"); user.Email = oldEmail; ModelState.Remove("User.Email"); } This allows you to remove a single value from the ModelState and effectively allows you to replace that value for display from the model. Why? While researching this I came across a post from Microsoft's Brad Wilson who describes the default binding behavior best in a forum post: The reason we use the posted value for editors rather than the model value is that the model may not be able to contain the value that the user typed. Imagine in your "int" editor the user had typed "dog". You want to display an error message which says "dog is not valid", and leave "dog" in the editor field. However, your model is an int: there's no way it can store "dog". So we keep the old value. If you don't want the old values in the editor, clear out the Model State. That's where the old value is stored and pulled from the HTML helpers. There you have it. It's not the most intuitive behavior, but in hindsight this behavior does make some sense even if at first glance it looks like you should be able to update values from the model. The solution of clearing ModelState works and is a reasonable one but you have to know about some of the innards of ModelState and how it actually works to figure that out.© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • My own HtmlHelper don't work in Asp.Net MVC 2

    - by name1ess0ne
    I have HtmlHelper in ASP.NET MVC 1. Now I wont to migrate to ASP.NET MVC 2, but this helper don't work =( public static string Image(this HtmlHelper helper, string url, string alt) { return string.Format("<img src=\"{0}\" alt=\"{1}\" />", url, alt); } public static string ImageLink<T>(this HtmlHelper helper, Expression<Action<T>> linkUrlAction, string imageUrlPath, string altText) where T : Controller { string linkUrl = helper.BuildUrlFromExpression(linkUrlAction);//compile time error string img = helper.Image(imageUrlPath, altText); string outputUrl = string.Format(@"<a href='{0}'>{1}</a>", linkUrl, img); return outputUrl; } Error: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'BuildUrlFromExpression' How I can fix this error?

    Read the article

  • How do I add dynamic htmlAttributes to htmlhelper ActionLinks?

    - by camainc
    In my master page I have a top-level menu that is created using ActionLinks: <ul id="topNav"> <li><%=Html.ActionLink("Home", "Index", "Home")%></li> <li><%=Html.ActionLink("News", "Index", "News")%></li> <li><%=Html.ActionLink("Projects", "Index", "Projects")%></li> <li><%=Html.ActionLink("About", "About", "Home")%></li> <li><%=Html.ActionLink("Contact", "Contact", "Home")%></li> <li><%=Html.ActionLink("Photos", "Photos", "Photos")%></li> </ul> I want to dynamically add a class named "current" to the link that the site is currently pointing to. So, for example, when the site is sitting at the home page, the menu link would render like this: <li><a class="current" href="/">Home</a></li> Do I have to overload the ActionLink method to do this, or create an entirely new HtmlHelper, or is there a better way? I'm fairly new to MVC, so I'm not sure what is the correct way to go about this. Thanks in advance.

    Read the article

  • Why isn't this MVC Html Helper extension method working?

    - by Blankman
    My base controller looks like: public abstract MyBaseMasterController<TMasterViewModel> : Controller { } public MyMasterController: MyBaseMasterController<SomeThingModel> { } Extension method: public static string DoSomething(this HtmlHelper htmlHelper) { StringBuilder sb = new StringBuilder(); sb.Append("var cnwglobals = {"); var controller = htmlHelper.ViewContext.Controller as MyMasterController; if (controller == null) { } return sb.ToString(); } In my view I do: <% Html.Dosomething(); %> I get an error: CS1061: 'System.Web.Mvc.HtmlHelper<Blah.Models.ViewModelForMasterWrapper<Blah.Models.MasterViewModel>>' does not contain a definition for 'DoSomething' and no extension method 'DoSomething' accepting a first argument of type 'System.Web.Mvc.HtmlHelper<Blah.Models.ViewModelForMasterWrapper<Blah.Models.MasterViewModel>>' could be found (are you missing a using directive or an assembly reference?)

    Read the article

  • How to protect HtmlHelper code in MVC controls

    - by Oats
    I am writing a custom mvc control (commercial), and all of the control's code lives in the custom htmlhelper code that i will have to distribute to the user. I am ok with this for my commercial license sale, but for evaluating the controls, if i give out the htmlhelper code locally for my potential customers to evaluate, the user can simply "get" all the code and hence he may never buy it since he's got teh control code. How do i protect my htmlhelper code while somebody is evaluation my cusotm mvc controls? Is this a general problem or (I wish) i am missing something here? Thanks.

    Read the article

  • What is the difference (if any) between Html.Partial(view, model) and Html.RenderPartial(view,model)

    - by Stephane
    Other than the type it returns and the fact that you call it differently of course <% Html.RenderPartial(...); %> <%= Html.Partial(...) %> If they are different, why would you call one rather than the other one? The definitions: // Type: System.Web.Mvc.Html.RenderPartialExtensions // Assembly: System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll using System.Web.Mvc; namespace System.Web.Mvc.Html { public static class RenderPartialExtensions { public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData); } } // Type: System.Web.Mvc.Html.PartialExtensions // Assembly: System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll using System.Web.Mvc; namespace System.Web.Mvc.Html { public static class PartialExtensions { public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData); } }

    Read the article

  • HtmlHelper does not contain definition for "Action"

    - by ognjenb
    I use <%= Html.Action("ReadXML") % and have this error: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'Action' and no extension method 'Action' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?) How fix it

    Read the article

  • What's wrong with my HtmlHelper?

    - by Dejan.S
    I done a htmlhelper but I can not get it to work tho. I did like I seen on different tutorials. my MenuItemHelper static Class public static string MenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName) { var currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"]; var currentActionName = (string)helper.ViewContext.RouteData.Values["action"]; var sb = new StringBuilder(); if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)) sb.Append("<li class=\"selected\">"); else sb.Append("<li>"); sb.Append(helper.ActionLink(linkText, actionName, controllerName)); sb.Append("</li>"); return sb.ToString(); } import namespace <%@ Import Namespace="MYAPP.Web.App.Helpers" %> Implementation on my master.page <%= Html.MenuItem("TEST LINK", "About", "Site") %> Errormessage I get Method not found: 'System.String System.Web.Mvc.Html.LinkExtensions.ActionLink(System.Web.Mvc.HtmlHelper, System.String, System.String, System.String)

    Read the article

  • Call asp.net mvc Html Helper within custom html helper with expression parameter

    - by Frank Michael Kraft
    I am trying to write an html helper extension within the asp.net mvc framework. public static MvcHtmlString PlatformNumericTextBoxFor<TModel>(this HtmlHelper instance, TModel model, Expression<Func<TModel,double>> selector) where TModel : TableServiceEntity { var viewModel = new PlatformNumericTextBox(); var func = selector.Compile(); MemberExpression memExpession = (MemberExpression)selector.Body; string name = memExpession.Member.Name; var message = instance.ValidationMessageFor<TModel, double>(selector); viewModel.name = name; viewModel.value = func(model); viewModel.validationMessage = String.Empty; var result = instance.Partial(typeof(PlatformNumericTextBox).Name, viewModel); return result; } The line var message = instance.ValidationMessageFor<TModel, double>(selector); has a syntax error. But I do not understand it. The error is: Fehler 2 "System.Web.Mvc.HtmlHelper" enthält keine Definition für "ValidationMessageFor", und die Überladung der optimalen Erweiterungsmethode "System.Web.Mvc.Html.ValidationExtensions.ValidationMessageFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression)" weist einige ungültige Argumente auf. C:\Projects\WorkstreamPlatform\WorkstreamPlatform_WebRole\Extensions\PlatformHtmlHelpersExtensions.cs 97 27 WorkstreamPlatform_WebRole So according to the message, the parameter is invalid. But the method is actually declared like this: public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression); So actually it should work.

    Read the article

  • Extension method not working if I set controller property in Action, works in OnExecuting

    - by Blankman
    I have a class MyController that inherits from Controller, so all my controllers inherit from MyController. I have a property in MyController: public class MyController : Controller { public string SomeProperty {get;set;} } if I set this property in MyController's OnExecuting method, my HtmlHelper extension method works fine: public static string SomeExtension(this HtmlHelper htmlHelper) { StringBuilder sb = new StringBuilder(); string result = ""; var controller = htmlHelper.ViewContext.Controller as MyController; if (controller != null) { result = controller.SomeProperty; } return result; } it doesn't work if I set 'SomeProperty' in my controllers action method. I guess because I am doing 'as MyController' in the extension method? is there a way for it to work in both situations? I am using the value of SomeProperty to be outputted on my view pages.

    Read the article

  • What is the easiest way to get the property value from a passed lambda expression in an extension me

    - by Andrew Siemer
    I am writing a dirty little extension method for HtmlHelper so that I can say something like HtmlHelper.WysiwygFor(lambda) and display the CKEditor. I have this working currently but it seems a bit more cumbersome than I would prefer. I am hoping that there is a more straight forward way of doing this. Here is what I have so far. public static MvcHtmlString WysiwygFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { return MvcHtmlString.Create(string.Concat("<textarea class=\"ckeditor\" cols=\"80\" id=\"", expression.MemberName(), "\" name=\"editor1\" rows=\"10\">", GetValue(helper, expression), "</textarea>")); } private static string GetValue<TModel, TProperty>(HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { MemberExpression body = (MemberExpression)expression.Body; string propertyName = body.Member.Name; TModel model = helper.ViewData.Model; string value = typeof(TModel).GetProperty(propertyName).GetValue(model, null).ToString(); return value; } private static string MemberName<T, V>(this Expression<Func<T, V>> expression) { var memberExpression = expression.Body as MemberExpression; if (memberExpression == null) throw new InvalidOperationException("Expression must be a member expression"); return memberExpression.Member.Name; } Thanks!

    Read the article

  • HTML Helper/Text Box validation

    - by slandau
    I have this input on the view: <%= Html.TextBoxCurrentDateWithoutPermission("EffectiveDate", Model.EffectiveDate.HasValue ? Model.EffectiveDate.Value.ToString("dd-MMM-yyyy") : "", new string[] { PERMISSIONS.hasICAdvanced }, new { @class = "economicTextBox", propertyName = "EffectiveDate", onchange = "parseAndSetDt(this); ", dataType = "Date" })%> Here is the custom HTML Helper: public static MvcHtmlString TextBoxCurrentDateWithoutPermission( this HtmlHelper htmlHelper, string name, object value, string[] permissions, object htmlAttributes ) { foreach (string permission in permissions) { if (Chatham.Web.UI.Extranet.SessionManager.DisplayUser.IsInRole(permission)) { // the user has the permission => render the textbox return htmlHelper.TextBox(name, value, htmlAttributes); } } // the user has no permission => render a readonly checkbox var mergedHtmlAttributes = new RouteValueDictionary(htmlAttributes); mergedHtmlAttributes["disabled"] = "disabled"; return htmlHelper.TextBox(name, value == "" ? DateTime.Now : value, mergedHtmlAttributes); } The way this works now is, when a user does NOT have the permission passed in, the box is disabled. The way it needs to be -- if the user does NOT have the permission passed in, it needs to be enabled, however the only dates it can accept are todays date AND dates in the future. So I need JQuery validation (or just plain JS), for this textbox on the page for the following case: If the textbox is enabled AND the user does not have the permission, allow the user to input the current date or future dates ONLY.

    Read the article

  • Creating a SelectListItem with the disabled="disabled" attribute

    - by Mark
    I realize Internet Explorer ignores the disabled attribute, but I'm not seeing a way to create, via the HtmlHelper, a SelectListItem that will spit out the following HTML: <option disabled="disabled">don't click this</option> The only properties SelectListItem has are: new SelectListItem{ Name = "don't click this", Value = string.Empty, Selected = false } The only option I see is to Subclass the SelectListItem to add an Enabled property to get the value to the view Not use the HTML helper for DropDownList Create a new HtmlHelper extension that accepts my new EnablableSelectList and adds my disabled attribute.

    Read the article

  • Mocking HtmlHelper throws NullReferenceException

    - by Matt Austin
    I know that there are a few questions on StackOverflow on this topic but I haven't been able to get any of the suggestions to work for me. I've been banging my head against this for two days now so its time to ask for help... The following code snippit is a simplified unit test to demonstrate what I'm trying to do, which is basically call RadioButtonFor in the Microsoft.Web.Mvc assembly in a unit test. var model = new SendMessageModel { SendMessageType = SendMessageType.Member }; var vd = new ViewDataDictionary(model); vd.TemplateInfo = new TemplateInfo { HtmlFieldPrefix = string.Empty }; var controllerContext = new ControllerContext(new Mock<HttpContextBase>().Object, new RouteData(), new Mock<ControllerBase>().Object); var viewContext = new Mock<ViewContext>(new object[] { controllerContext, new Mock<IView>().Object, vd, new TempDataDictionary(), new Mock<TextWriter>().Object }); viewContext.Setup(v => v.View).Returns(new Mock<IView>().Object); viewContext.Setup(v => v.ViewData).Returns(vd).Callback(() => {throw new Exception("ViewData extracted");}); viewContext.Setup(v => v.TempData).Returns(new TempDataDictionary()); viewContext.Setup(v => v.Writer).Returns(new Mock<TextWriter>().Object); viewContext.Setup(v => v.RouteData).Returns(new RouteData()); viewContext.Setup(v => v.HttpContext).Returns(new Mock<HttpContextBase>().Object); viewContext.Setup(v => v.Controller).Returns(new Mock<ControllerBase>().Object); viewContext.Setup(v => v.FormContext).Returns(new FormContext()); var mockContainer = new Mock<IViewDataContainer>(); mockContainer.Setup(x => x.ViewData).Returns(vd); var helper = new HtmlHelper<ISendMessageModel>(viewContext.Object, mockContainer.Object, new RouteCollection()); helper.RadioButtonFor(m => m.SendMessageType, "Member", cssClass: "selector"); If I remove the cssClass parameter then the code works ok but fails consistently when adding additional parameters. I've tried every combination of mocking, instantiating concrete types and using fakes that I can think off but I always get a NullReferenceException when I call RadioButtonFor. Any help hugely appreciated!!

    Read the article

  • ASP.NET MVC Html Helper Extensions and Rendering Their Required "include"s

    - by Jimbo
    I have build a custom Html Helper extension as follows: public static string DatePicker(this HtmlHelper helper, string name, string value) { return string.Format(@"<script type='text/javascript'> $(document).ready(function(){{ $('#{0}').datepicker({{ changeMonth: true, changeYear:true, dateFormat: 'd-M-yy', firstDay: 1, showButtonPanel: true, showWeek: true }}); }}); </script> <input type='text' name='{0}' id='{0}' value='{1}'>", name, value); } The problem is that this now requires the page to "include" the following: <script src="/Scripts/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="/Scripts/jquery.ui.datepicker.min.js" type="text/javascript"></script> And a few other items. The questions are as follows: Is there a serious processing overhead if I were to include these items in EVERY page (like in the Site.Master for example) thus negating the need for the HtmlHelper to organise the "includes" - considering there would end up being about 20 includes for all the different types of jQuery UI widgets used throughout the site. If the HtmlHelper sorts out the "includes", it will add one every time this DatePicker is used (often there are two on a page) Does anyone have a way of determining whether or not the user has already rendered the same type of control on the page, thus not re-including the same jquery libraries when multiple instances of the DatePicker (for example) are used?

    Read the article

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