Search Results

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

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

  • Naming of ASP.NET controls inside User Controls with ASP.NET MVC

    - by skb
    I am wondering if there is a way to make ASP.NET controls play nicely with my ASP.NET MVC app. Here is what I am doing. I have an order page which displays info about a single Order object. The page will normally have a bunch of rows of data, each row representing an OrderItem object. Each row is an ASP.NET User Control. On the user control there is a form element with two text boxes (Quantity and Price), and an update button. When I click the update button, I expect the form to post the data for that individual OrderItem row to a controller method and update the OrderItem record in the database. Here is my problem: When the post happens, the framework complains because the fields on the form don't match the parameters on the controller method. Each form field is something like "OrderItem_1$Quantity" or "OrderItem_2$Price" instead of just "Quantity" or "Price" which would match my method parameters. I have been told that I can overcome this by making sure that the IDs of all my controls are unique for the page, but allow the NAMEs to be repeated between different forms, so that if a form for an individual row is posted, the name can be something that will match what is on my controller method. The only problem is that I am using ASP.NET controls for my text boxes (which I REALLY want to continue doing) and I can't find any way to override the name field. There is no Name propery on an ASP.NET control, and even when I try to set it using the Attributes accessor property by saying "control.Attributes["Name"] = "Price";" it just adds another name= attribute to the HTML tag which doesn't work. Does any one know how I can make this work? I really don't like all of the HtmlHelper functions like TextBox and DropDown because I hate having my .aspx be so PHP or ASP like with the <%% tags and everything. Thanks!

    Read the article

  • Selected Item in Dropdown Lists from Enum in ASP.net MVC

    - by AlexCuse
    Sorry if this is a dup, my searching turned up nothing. I am using the following method to generate drop down lists for enum types (lifted from here: http://addinit.com/?q=node/54): public static string DropDownList(this HtmlHelper helper, string name, Type type, object selected) { if (!type.IsEnum) throw new ArgumentException("Type is not an enum."); if(selected != null && selected.GetType() != type) throw new ArgumentException("Selected object is not " + type.ToString()); var enums = new List<SelectListItem>(); foreach (int value in Enum.GetValues(type)) { var item = new SelectListItem(); item.Value = value.ToString(); item.Text = Enum.GetName(type, value); if(selected != null) item.Selected = (int)selected == value; enums.Add(item); } return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, enums, "--Select--"); } It is working fine, except for one thing. If I give the dropdown list the same name as the property on my model the selected value is not set properly. Meaning this works: <%= Html.DropDownList("fam", typeof(EnumFamily), Model.Family)%> But this doesn't: <%= Html.DropDownList("family", typeof(EnumFamily), Model.Family)%> Because I'm trying to pass an entire object directly to the controller method I am posting to, I would really like to have the dropdown list named for the property on the model. When using the "right" name, the dropdown does post correctly, I just can't seem to set the selected value. I don't think this matters but I am running MVC 1 on mono 2.6

    Read the article

  • ASP.NET MVC: Html.Actionlink() generates empty link.

    - by wh0emPah
    Okay i'm experiencing some problems with the actionlink htmlhelper. I have some complicated routing as follows: routes.MapRoute("Groep_Dashboard_Route", // Route name "{EventName}/{GroupID}/Dashboard", // url with Paramters new {controller = "Group", action="Dashboard"}); routes.MapRoute("Event_Groep_Route", // Route name "{EventName}/{GroupID}/{controller}/{action}/{id}", new {controller = "Home", action = "Index"}); My problem is generating action links that match these patterns. The eventname parameter is really just for having a user friendly link. it doesn't do anything. Now when i'm trying for example to generate a link. that shows the dashboard of a certain groep. Like: mysite.com/testevent/20/Dashboard I'll use the following actionlink: <%: Html.ActionLink("Show dashboard", "Group", "Dashboard", new { EventName_Url = "test", GroepID = item.groepID}, null)%> What my actual result in html gives is: <a href="">Show Dashboard</a> Please bear with me i'm still new at ASP MVC. Could someone tell me what i'm doing wrong? Help would be appreciated!

    Read the article

  • Post-loading : check if an image is in the browser cache

    - by Mathieu
    Short version question : Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers, or an alternative? Long version :) Hi, Here is my situation : I want to implement an HtmlHelper extension for asp.net MVC that handle image post-loading easily (using jQuery). So i render the page with empty image sources with the source specified in the "alt" attribute. I insert image sources after the "window.onload" event, and it works great. I did something like this : $(window).bind('load', function() { var plImages = $(".postLoad"); plImages.each(function() { $(this).attr("src", $(this).attr("alt")); }); }); The problem is : After the first loading, post-loaded images are cached. But if the page takes 10 seconds to load, the cached post-loaded images will be displayed after this 10 seconds. So i think to specify image sources on the "document.ready" event if the image is cached to display them immediatly. I found this function : navigator.mozIsLocallyAvailable to check if an image is in the cache. Here is what I've done with jquery : //specify cached image sources on dom ready $(document).ready(function() { var plImages = $(".postLoad"); plImages.each(function() { var source = $(this).attr("alt") var disponible = navigator.mozIsLocallyAvailable(source, true); if (disponible) $(this).attr("src", source); }); }); //specify uncached image sources after page loading $(window).bind('load', function() { var plImages = $(".postLoad"); plImages.each(function() { if ($(this).attr("src") == "") $(this).attr("src", $(this).attr("alt")); }); }); It works on Mozilla's DOM but it doesn't works on any other one. I tried navigator.isLocallyAvailable : same result. Is there any alternative?

    Read the article

  • MVC: model of type Nullable<T>

    - by Fyodor Soikin
    I have a partial view that inherits from ViewUserControl<Guid?> - i.e. it's model is of type Nullable<Guid>. Very simple view, nothing special, but that's not the point. Somewhere else, I do Html.RenderPartial( "MyView", someGuid ), where someGuid is of type Nullable<Guid>. Everything's perfectly legal, should work OK, right? But here's the gotcha: the second argument of Html.RenderPartial is of type object, and therefore, Nullable<Guid> being a value type, it must be boxed. But nullable types are somehow special in the CLR, so that when you box one of those, you actually get either a boxed value of type T (Nullable's argument), or a null if the nullable didn't have a value to begin with. And that last case is actually interesting. Turns out, sometimes, I do have a situation when someGuid.HasValue == false. And in those cases, I effectively get a call Html.RenderPartial( "MyView", null ). And what does the HtmlHelper do when the model is null? Believe it or not, it just goes ahead and takes the parent view's model. Regardless of it's type. So, naturally, in those cases, I get an exception saying: "The model item passed into the dictionary is of type 'Parent.View.Model.Type', but this dictionary requires a model item of type 'System.Guid?'" So the question is: how do I make MVC correctly pass new Nullable<Guid> { HasValue = false } instead of trying to grab the parent's model? Note: I did consider wrapping my Guid? in an object of another type, specifically created for this occasion, but this seems completely ridiculous. Don't want to do that as long as there's another way. Note 2: now that I've wrote all this, I've realized that the question may be reduced to how to pass a null for model without ending up with parent's model?

    Read the article

  • How to "escape" the JavaScript class keyword to specify a CSS class value.

    - by Robert Claypool
    C# allows a reserved word to be used as a property name via the ampersand. e.g. // In ASP.NET MVC, we use @class to define // the css class attribute for some HtmlHelper methods. var htmlObject = new { readonly = "readonly", @class = "ui-state-highlight" } I want to do the same in JavaScript. e.g. function makeGrid(grid, pager) { grid.jqGrid({ caption: 'Configurations', colNames: ['Id', 'Name'], colModel: [ { name: 'Id', index: 'Id' }, { name: 'Name', index: 'Name', editable: true, editoptions: { readonly: 'readonly', class: 'FormElement readonly' } }, ], pager: pager, url: 'www.example.com/app/configurations") %>', editurl: 'www.example.com/app/configurations/edit") %>' }).navGrid(pager, { edit: true, add: false, del: false, search: false }, {}, {}, {}); } Note class: 'FormElement readonly' is supposed to set the css class value on jqGrid's edit dialog, but IE errors out on the reserved word. Is there an escape character in JavaScript too? #class? @class? &class? Otherwise, how might I tell jqGrid to set the css class on the popup editor? Thank you.

    Read the article

  • ASP.NET MVC static-asset aides/practices

    - by shannon
    I want to keep assets that are only used by one view in a view-specific folder, so my Search.aspx properly finds images/*.jpg, and helps me maintain my convention: ~/Areas/Candidate/Views/Job/Search.aspx -> ~/Assets/Candidate/Job/Search/images/*.jpg Perhaps with the ability to easily reference controller- or area-common assets manually or automatically: ~/Assets/Candidate/Job/images/*.jpg ~/Assets/Candidate/images/*.jpg If you wonder why I'm doing this, then speak up; I'm probably missing something. But here's why: I don't want stale static assets sitting in my ASP.NET MVC projects, which I expect to be an automatic outcome of the ~/Assets/Images folder: i.e. As a shared asset loses its last reference-count, who knows to delete it, especially with it being so difficult to trace content link validity in MVC projects? How do you, personally, do this? I can imagine, for example: Implement HtmlHelper extension methods for URL-generation. Extending ViewPage and ViewMasterPage with URL-generation methods. Implementing an inbound request filter to search related folders for static assets. and, are there good libraries out there for this? For example, something that also automatically appends timestamps for .JS and .CSS files, writes the / tags for me, and maybe even that allows me to inject includes in the head section from outside head code?

    Read the article

  • paging helper asp.net mvc

    - by csetzkorn
    Hi, I have implemented a paging html helper (adapted from steven sanderson's book). This is the current code: public static string PageLinks(this HtmlHelper html, int currentPage, int totalPages, Func pageUrl) { StringBuilder result = new StringBuilder(); for (int i = 1; i <= totalPages; i++) { TagBuilder tag = new TagBuilder("a"); tag.MergeAttribute("href", pageUrl(i)); tag.InnerHtml = i.ToString(); if (i == currentPage) tag.AddCssClass("selectedPage"); result.AppendLine(tag.ToString()); } return result.ToString(); } This produces a bunch of links to each page of my items. If there are many pages this can be a bit overwhelming. I am looking for a similar implementation which produces something less overwhelming like this: where 6 is the current page. I am sure someone must have implemented something similar ... before I have to re-implement the wheel. Thanks. Christian

    Read the article

  • Basic Question on storing variables c# for use in other classes

    - by Calibre2010
    Ok guys I basically have a class which takes in 3 strings through the parameter of one of its method signatures. I've then tried to map these 3 strings to global variables as a way to store them. However, when I try to call these global variables from another class after instantiating this class they display as null values. this is the class which gets the 3 strings through the method setDate, and the mapping.. public class DateLogic { public string year1; public string month1; public string day1; public DateLogic() { } public void setDate(string year, string month, string day) { year1 = year; month1 = month; day1 = day; // getDate(); } public string getDate() { return year1 + " " + month1 + " " + day1; } } After this I try call this class from here public static string TimeLine2(this HtmlHelper helper, string myString2) { DateLogic g = new DateLogic(); string sday = g.day1; string smonth = g.month1; string syr = g.year1; } I've been debugging and the values make it all the way to the global variables but when called from this class here it doesnt show them, just shows null. Is this cause I'm creating a brand new instance, how do i resolve this?

    Read the article

  • Trouble with Router::url() when using named parameters

    - by sibidiba
    I'm generating plain simple links with CakePHP's HtmlHelper the following way: $html->link("Newest", array( 'controller' => 'posts', 'action' => 'listView', 'page'=> 1, 'sort'=>'Question.created', 'direction'=>'desc', )); Having the following route rule: Router::connect('/foobar/*',array( 'controller' => 'posts', 'action' => 'listView' )); The link is nicely generated as /foobar/page:1/sort:Question.created/direction:desc. Just as I want, it uses my URL prefix instead of controller/action names. However, for some links I must add named parameters like this: $html->link("Newest", array( 'controller' => 'posts', 'action' => 'listView', 'page'=> 1, 'sort'=>'Question.created', 'direction'=>'desc', 'namedParameter' => 'namedParameterValue' )); The link in this case points to /posts/listView/page:1/sort:Question.created/direction:desc/namedParameter:namedParameterValue. But I do not want to have contoller/action names in my URL-s, why is Cake ignoring in this case my routers configuration?

    Read the article

  • How use unobtrusive validation without a model

    - by Ross Cyrus
    i have simple a form wich made by htmlHelper(mvc3) then inside of it i have 2 input field 1:type=text 2:type=submit to submit the form. there is no model behind.so i need to perfom a clientside validation on the textfield before submit it to the server.but i dont know how. i tried this puting manualy the 'data-* artibute , but does not work : @using( Html.BeginForm()) { <label for="UserName" >User Name</label> <div class="editor-field"> <input type="text" data-val="true" data-val-requierd="You must provide an user Name" id="userName" name="userName" placeholder="Enter Your User Name" /> </div> <input type="submit" value="Recover" /> } the "jquery.validate.min.js" and jquery.validate.unobtrusive.min.js and jquery.validate.min.js and jquery.validate.unobtrusive.min.js are loaded to the page. It doesnt let me to answer my self ,so i put it here : I solve it my self,just made an other view wich has its own model and Required on its propertyis and then just copy the renderd html to my own,and i got this and works : <input data-val="true" data-val-required="You must provide an user Name" id="UserName" name="UserName" type="text" value="" placeholder="Enter your User Name"/> <span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span> And there is no type="Required".any way thank you guys.

    Read the article

  • Abstracting the interpretation of MVC checkboxes values received by the FormsCollection object

    - by Simon_Weaver
    In ASP.NET MVC a checkbox is generated by the HtmlHelper code here: <%= Html.CheckBox("List_" + mailingList.Key, true) %> as this HTML: <input id="List_NEW_PRODUCTS" name="List_NEW_PRODUCTS" type="checkbox" value="true" /> <input name="List_NEW_PRODUCTS" type="hidden" value="false" /> In case you're wondering why is there an extra hidden field? - then read this. Its definitely a solution that makes you first think 'hmmmmm' but then you realize its a pretty elegant one. The problem I have is when I'm trying to parse the data on the backend. Well its not so much of a problem as a concern if anything in future were to change in the framework. If I'm using the built in binding everything is great - its all done for me. But in my case I'm dynamically generating checkboxes with unknown names and no corresponding properties in my model. So i end up having to write code like this : if (forms["List_RETAIL_NOTIFICATION"] == "true,false") { } or this: if (forms.GetValues("List_RETAIL_NOTIFICATION")[0] == "true") { } Both of which i still look at and cringe - especially since theres no guarantee this will always be the return value. I'm wondering if theres a way to access the layer of abstraction used by the model binders - or if I'm stuck with my controller 'knowing' this much about HTTP POST hacks. Yes I'm maybe being a little picky - but perhaps theres a better clever way using the model binders that I can employ to read dynamically created checkbox parameters. In addition i was hoping this this post might help others searcheing for : "true,false". Even though I knew why it does this I just forgot and it took me a little while to realize 'duh'. FYI: I tried another few things, and this is what I found : forms["List_RETAIL_NOTIFICATION"] evaluates to "true,false" forms.GetValues("List_RETAIL_NOTIFICATION")[0] evaluates to "true" (forms.GetValue("List_RETAIL_NOTIFICATION").RawValue as string[])[0] evaluates to "true" forms.GetValues("List_RETAIL_NOTIFICATION").FirstOrDefault() evaluates to "true"

    Read the article

  • Guarding against CSRF Attacks in ASP.NET MVC2

    - by srkirkland
    Alongside XSS (Cross Site Scripting) and SQL Injection, Cross-site Request Forgery (CSRF) attacks represent the three most common and dangerous vulnerabilities to common web applications today. CSRF attacks are probably the least well known but they are relatively easy to exploit and extremely and increasingly dangerous. For more information on CSRF attacks, see these posts by Phil Haack and Steve Sanderson. The recognized solution for preventing CSRF attacks is to put a user-specific token as a hidden field inside your forms, then check that the right value was submitted. It's best to use a random value which you’ve stored in the visitor’s Session collection or into a Cookie (so an attacker can't guess the value). ASP.NET MVC to the rescue ASP.NET MVC provides an HTMLHelper called AntiForgeryToken(). When you call <%= Html.AntiForgeryToken() %> in a form on your page you will get a hidden input and a Cookie with a random string assigned. Next, on your target Action you need to include [ValidateAntiForgeryToken], which handles the verification that the correct token was supplied. Good, but we can do better Using the AntiForgeryToken is actually quite an elegant solution, but adding [ValidateAntiForgeryToken] on all of your POST methods is not very DRY, and worse can be easily forgotten. Let's see if we can make this easier on the program but moving from an "Opt-In" model of protection to an "Opt-Out" model. Using AntiForgeryToken by default In order to mandate the use of the AntiForgeryToken, we're going to create an ActionFilterAttribute which will do the anti-forgery validation on every POST request. First, we need to create a way to Opt-Out of this behavior, so let's create a quick action filter called BypassAntiForgeryToken: [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] public class BypassAntiForgeryTokenAttribute : ActionFilterAttribute { } Now we are ready to implement the main action filter which will force anti forgery validation on all post actions within any class it is defined on: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class UseAntiForgeryTokenOnPostByDefault : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (ShouldValidateAntiForgeryTokenManually(filterContext)) { var authorizationContext = new AuthorizationContext(filterContext.Controller.ControllerContext);   //Use the authorization of the anti forgery token, //which can't be inhereted from because it is sealed new ValidateAntiForgeryTokenAttribute().OnAuthorization(authorizationContext); }   base.OnActionExecuting(filterContext); }   /// <summary> /// We should validate the anti forgery token manually if the following criteria are met: /// 1. The http method must be POST /// 2. There is not an existing [ValidateAntiForgeryToken] attribute on the action /// 3. There is no [BypassAntiForgeryToken] attribute on the action /// </summary> private static bool ShouldValidateAntiForgeryTokenManually(ActionExecutingContext filterContext) { var httpMethod = filterContext.HttpContext.Request.HttpMethod;   //1. The http method must be POST if (httpMethod != "POST") return false;   // 2. There is not an existing anti forgery token attribute on the action var antiForgeryAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), false);   if (antiForgeryAttributes.Length > 0) return false;   // 3. There is no [BypassAntiForgeryToken] attribute on the action var ignoreAntiForgeryAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(BypassAntiForgeryTokenAttribute), false);   if (ignoreAntiForgeryAttributes.Length > 0) return false;   return true; } } The code above is pretty straight forward -- first we check to make sure this is a POST request, then we make sure there aren't any overriding *AntiForgeryTokenAttributes on the action being executed. If we have a candidate then we call the ValidateAntiForgeryTokenAttribute class directly and execute OnAuthorization() on the current authorization context. Now on our base controller, you could use this new attribute to start protecting your site from CSRF vulnerabilities. [UseAntiForgeryTokenOnPostByDefault] public class ApplicationController : System.Web.Mvc.Controller { }   //Then for all of your controllers public class HomeController : ApplicationController {} What we accomplished If your base controller has the new default anti-forgery token attribute on it, when you don't use <%= Html.AntiForgeryToken() %> in a form (or of course when an attacker doesn't supply one), the POST action will throw the descriptive error message "A required anti-forgery token was not supplied or was invalid". Attack foiled! In summary, I think having an anti-CSRF policy by default is an effective way to protect your websites, and it turns out it is pretty easy to accomplish as well. Enjoy!

    Read the article

  • jQuery Templates, Data Link

    - by Renso
    Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} Query Templates, Data Link, and Globalization I am sure you must have read Scott Guthrie’s blog post about jQuery support and officially supporting jQuery's templating, data linking and globalization, if not here it is: jQuery Templating Since we are an open source shop and use jQuery and jQuery plugins extensively to say the least, decided to look into the templating a bit and see what data linking is all about. For those not familiar with those terms here is the summary, plenty of material out there on what it is, but here is what in my experience it means: jQuery Templating: A templating engine that allows you to specify a client-side template where you indicate which properties/tags you want dynamically updated. You in a sense specify which parts of the html is dynamic and since it is pluggable you are able to use tools data jQuery data linking and others to let it sync up your template with data. What makes it more powerful is that you can easily work with rows of data, adding and removing rows. Once the template has been generated, which you do dynamically on a client-side event, you then append/inject the resulting template somewhere in your DOM, like for example you would get a JSON object from the database, map it to your template, it populates the template with your data in the indicated places, and then let’s say for example append it to a row in a table. I have not found it that useful for lets say a single record of data since you could easily just get a partial view from the server via an html type ajax call. It really shines when you dynamically add/remove rows from a list in the DOM. I have not found an alternative that meets the functionality of the jQuery template and helps of course that Microsoft officially supports it. In future versions of the jQuery plug-in it may even ship as part of the standard jQuery library and with future versions of Visual Studio. jQuery Data Linking: In short I was fascinated by it initially by how with one line of code I can sync up my JSON object with my form elements. That's where my enthusiasm stopped. It was one-line to let is deal with syncing up your form with your JSON object, but it is not bidirectional as they state and I tried all the work arounds they suggested and none of them work. The problem is that when you update your JSON object it DOES NOT sync it up with your form. In an example, accounts are being edited client side by selecting the account from a list by clicking on the row, it then fetches the entire account JSON object via ajax json-type call and then refreshes the form with the account’s details from the new JSON object. What is the use of syncing up my JSON with the form if I still have to programmatically sync up my new JSON object with each DOM property?! So you may ask: “what is the alternative”? Good question and the same one I was pondering, maybe I can just use it for keeping my from n sync with my JSON object so I can post that JSON object back to the server and update my database. That’s when I discovered Knockout: Knockout It addresses the issues mentioned above and also supports event handling through the observer pattern. Not wanting to go into detail here, Steve Sanderson, the creator of Knockout, has already done a terrific job of that, thanks Steve for a great plug-in! Best of all it integrates perfectly with the jQuery Templating engine as well. I have not found an alternative to this plugin that supports the depth and width of functionality and would recommend it to anyone. The only drawback is the embedded html attributes (data-bind=””) tags that you have to add to the HTML, in my opinion tying your behavior to your HTML, where I like to separate behavior from HTML as well as CSS, so the HTML is purely to define content, not styling or behavior. But there are plusses to this as well and also a nifty work around to this that I will just shortly mention here with an example. Instead of data binding an html tag with knockout event handling like so:  <%=Html.TextBox("PrepayDiscount", String.Empty, new { @class = "number" })%>   Do: <%=Html.DataBoundTextBox("PrepayDiscount", String.Empty, new { @class = "number" })%>   The html extension above then takes care of the internals and you could then swap Knockout for something else if you want to inside the extension and keep the HTML plugin agnostic. Here is what the extension looks like, you can easily build a whole library to support all kinds of data binding options from this:      public static class HtmlExtensions       {         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextBox(name, value, dic);         }       }   Hope this helps in making a decision when and where to consider jQuery templating, data linking and Knockout.

    Read the article

  • Html.EditorFor not updating model on post

    - by Dave
    I have a complex type composed of two nullable DateTimes: public class Period { public DateTime? Start { get; set; } public DateTime? End { get; set; } public static implicit operator string(Period period) { /* converts from Period to string */ } public static implicit operator Period(string value) { /* and back again */ } } I want to display them together in a single textbox as a date range so I can provide a nice jQuery UI date range selector. To make that happen have the following custom editor template: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Period>" %> <% string name = ViewData.TemplateInfo.HtmlFieldPrefix; %> <%= Html.PeriodTextBox(name, Model.EarliestDate, Model.LatestDate) %> Where Html.PeriodTextBox is an extension method I've written that just concatenates the two dates sensibly, turns off autocomplete and generates a textbox, like so: public static MvcHelperString PeriodTextBox(this HtmlHelper helper, string name, DateTime? startDate, DateTime? endDate) { TagBuilder builder = new TagBuilder("input"); builder.GenerateId(name); builder.Attributes.Add("name", name); builder.Attributes.Add("type", "text"); builder.Attributes.Add("autocomplete", "off"); builder.Attributes.Add("value", ConcatDates(startDate, endDate)); return MvcHtmlString.Create(builder.ToString()); } That's working fine in that I can call <%= Html.EditorFor(m => m.ReportPeriod) %> and I get my textbox, then when the form is submitted the FormCollection passed to the post action will contain an entry named ReportPeriod with the correct value. [HttpPost] public ActionResult ReportByRange(FormCollection formValues) { Period reportPeriod = formValues["ReportPeriod"]; // creates a Period, with the expected values } The problem is if I replace the FormCollection with the model type I'm passing to the view then the ReportPeriod property never gets set. [HttpPost] public ActionResult ReportByRange(ReportViewModel viewModel) { Period reportPeriod = viewModel.ReportPeriod; // this is null } I expected MVC would try to set the string from the textbox to that property and it would automatically generate a Period (as in my FormCollection example), but it's not. How do I tell the textbox I've generated in the custom editor to poplate that property on the model?

    Read the article

  • Building a template to auto-scaffold Index views in ASP.NET MVC

    - by DanM
    I'm trying to write an auto-scaffolder 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; // Should be 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) { %> <tr> <% foreach(var property in properties) { %> <td> <%= Html.Display(property.DisplayName) %> // This doesn't work! </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. The <td> elements are not working because the Html in <%= Html.Display(property.DisplayName) %> contains the model for the view, which is a collection of items, not the item itself. Somehow, I need to obtain an HtmlHelper object whose Model property is the current item, but I'm not sure how to do that. How do I solve these two problems?

    Read the article

  • Why is Html.DropDownList() producing <select name="original_name.name"> instead of just <select name

    - by DanM
    I have an editor template whose job is to take a SelectList as its model and build a select element in html using the Html.DropDownList() helper extension. I'm trying to assign the name attribute for the select based on a ModelMetadata property. (Reason: on post-back, I need to bind to an object that has a different property name for this item than the ViewModel used to populate the form.) The problem I'm running into is that DropDownList() is appending the name I'm providing instead of replacing it, so I end up with names like categories.category instead of category. Here is some code for you to look at... SelectList.ascx <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Web.Mvc.SelectList>" %> <%= Html.DropDownList( (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"], Model) %> Resulting HTML <select id="SkillLevels_SkillLevel" name="SkillLevels.SkillLevel"> <option value="1">High</option> <option value="2">Med</option> <option selected="selected" value="3">Low</option> </select> Expected HTML <select id="SkillLevels_SkillLevel" name="SkillLevel"> <option value="1">High</option> <option value="2">Med</option> <option selected="selected" value="3">Low</option> </select> Also tried <%= Html.Encode((string)ViewData.ModelMetadata.AdditionalValues["PropertyName"])%> ...which resulted in "SkillLevel" (not "SkillLevels.SkillLevel"), proving that the data stored in metadata is correct. and <%= Html.DropDownList( (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"], Model, new { name = (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"] }) %> ...which still resulted in <select name=SkillLevels.Skilllevel>. Questions What's going on here? Why does it append the name instead of just using it? Can you suggest a good workaround? Update: I ended up writing a helper extension that literally does a find/replace on the html text: public static MvcHtmlString BindableDropDownListForModel(this HtmlHelper helper) { var propertyName = (string)helper.ViewData.ModelMetadata.AdditionalValues["PropertyName"]; var compositeName = helper.ViewData.ModelMetadata.PropertyName + "." + propertyName; var rawHtml = helper.DropDownList(propertyName, (SelectList)helper.ViewData.Model); var bindableHtml = rawHtml.ToString().Replace(compositeName, propertyName); return MvcHtmlString.Create(bindableHtml); }

    Read the article

  • Auto-scaffolding an "index" view in ASP.NET MVC

    - by DanM
    I'm trying to write an auto-scaffolder 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; // Should be 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) { %> <tr> <% foreach(var property in properties) { %> <td> <%= Html.Display(property.DisplayName) %> // This doesn't work! </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. The <td> elements are not working because the Html in <%= Html.Display(property.DisplayName) %> contains the model for the view, which is a collection of items, not the item itself. Somehow, I need to obtain an HtmlHelper object whose Model property is the current item, but I'm not sure how to do that. How do I solve these two problems?

    Read the article

  • ASP MVC 2: Error with dropdownlist on POST

    - by wh0emPah
    Okay i'm new to asp mvc2 and i'm experiencing some problems with the htmlhelper called Html.dropdownlistfor(); I want to present the user a list of days in the week. And i want the selected item to be bound to my model. I have created this little class to generate a list of days + a short notation which i will use to store it in the database. public static class days { public static List<Day> getDayList() { List<Day> daylist = new List<Day>(); daylist.Add(new Day("Monday", "MO")); daylist.Add(new Day("Tuesday", "TU")); // I left the other days out return daylist; } public class Dag{ public string DayName{ get; set; } public string DayShortName { get; set; } public Dag(string name, string shortname) { this.DayName= name; this.DayShortName = shortname; } } } I really have now idea if this is the correct way to do it Then i putted this in my controller: SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName"); ViewData["days"] = _list; return View(""); I have this line in my model public string ChosenDay { get; set; } And this in my view to display the list: <div class="editor-field"> <%: Html.DropDownListFor(model => model.ChosenDay, ViewData["days"] as SelectList, "--choose Day--")%> </div> Now this all works perfect. On the first visit, But then when i'm doing a [HttpPost] Which looks like the following: [HttpPost] public ActionResult Registreer(EventRegistreerViewModel model) { // I removed some unrelated code here // The code below executes when modelstate.isvalid == false SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName"); ViewData["days"] = _list; return View(model); } Then i will have the following exception thrown: The ViewData item that has the key 'ChosenDay' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'. This errors gets thrown at the line in my view where i display the dropdown list. I really have no idea how to solve this and tried several solutions i found online. but none of them really worked. Ty in advance!

    Read the article

  • Auto-scaffolding Index views in ASP.NET MVC

    - by DanM
    I'm trying to write an auto-scaffolder 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; // Should be 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) { %> <tr> <% foreach(var property in properties) { %> <td> <%= Html.Display(property.DisplayName) %> // This doesn't work! </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. The <td> elements are not working because the Html in <%= Html.Display(property.DisplayName) %> contains the model for the view, which is a collection of items, not the item itself. Somehow, I need to obtain an HtmlHelper object whose Model property is the current item, but I'm not sure how to do that. How do I solve these two problems?

    Read the article

  • Grouping Months of a particular Time span together using DateTime.

    - by Calibre2010
    public static string TimeLine2(this HtmlHelper helper, string myString2) { StringBuilder myString3 = new StringBuilder(); DateTime start = new DateTime(2010, 1, 1); DateTime end = new DateTime(2011, 12, 12); myString3.Append("<table>"); myString3.Append("<tr>"); for (DateTime date = start; date <= end; date = date.AddDays(1)) { DayOfWeek dw = date.DayOfWeek; var g = date.Month; var sun = " "; switch (dw) { case DayOfWeek.Sunday: sun = "S"; break; case DayOfWeek.Monday: sun = "M"; break; case DayOfWeek.Tuesday: sun = "T"; break; case DayOfWeek.Wednesday: sun = "W"; break; case DayOfWeek.Thursday: sun = "T"; break; case DayOfWeek.Friday: sun = "F"; break; case DayOfWeek.Saturday: sun = "S"; break; } myString3.Append("<td>" + sun + " " + g + "</td>"); } myString3.Append("</tr>"); myString3.Append("<tr>"); for (DateTime date = start; date <= end; date = date.AddDays(1)) { var f = date.Day; myString3.Append("<td>" + f + "</td>"); } myString3.Append("</tr>"); myString3.Append("</table>"); return myString3.ToString(); } Basically, what I have here is a few loops showing all the days of the week and also all the days in a month. This is all placed inside of a table, so you get MTWTFSSMT W T F S S M M TWTFSSM 12345678910 11 12 13 14 + + to 31 1234567 I'm trying to code a way in which I can split all of these days of the week and days in months so that my code returns each month with all its days in the month and all its days of the week, not just all my months between my timeSpan but splits them so MAY MTWTFSSMTWTFSSMTWTFSSMTWTFSSMTWTF 12345678 JUNE MTWTFSSMTWTFSSMTWTFSSMTWTFSSMTWTF 123456789

    Read the article

  • Need help with auto-scaffolding template in ASP.NET MVC

    - by DanM
    I'm trying to write an auto-scaffolder 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; // Should be 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) { %> <tr> <% foreach(var property in properties) { %> <td> <%= Html.Display(property.DisplayName) %> // This doesn't work! </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. The <td> elements are not working because the Html in <%= Html.Display(property.DisplayName) %> contains the model for the view, which is a collection of items, not the item itself. Somehow, I need to obtain an HtmlHelper object whose Model property is the current item, but I'm not sure how to do that. How do I solve these two problems?

    Read the article

  • Inline HTML Syntax for Helpers in ASP.NET MVC

    - by kouPhax
    I have a class that extends the HtmlHelper in MVC and allows me to use the builder pattern to construct special output e.g. <%= Html.FieldBuilder<MyModel>(builder => { builder.Field(model => model.PropertyOne); builder.Field(model => model.PropertyTwo); builder.Field(model => model.PropertyThree); }) %> Which outputs some application specific HTML, lets just say, <ul> <li>PropertyOne: 12</li> <li>PropertyTwo: Test</li> <li>PropertyThree: true</li> </ul> What I would like to do, however, is add a new builder methid for defining some inline HTML without having to store is as a string. E.g. I'd like to do this. <% Html.FieldBuilder<MyModel>(builder => { builder.Field(model => model.PropertyOne); builder.Field(model => model.PropertyTwo); builder.ActionField(model => %> Generated: <%=DateTime.Now.ToShortDate()%> (<a href="#">Refresh</a>) <%); }).Render(); %> and generate this <ul> <li>PropertyOne: 12</li> <li>PropertyTwo: Test</li> <li>Generated: 29/12/2008 <a href="#">Refresh</a></li> </ul> Essentially an ActionExpression that accepts a block of HTML. However to do this it seems I need to execute the expression but point the execution of the block to my own StringWriter and I am not sure how to do this. Can anyone advise?

    Read the article

  • Issue with TagBuilder.MergeAttribute for parameter null

    - by The Yur
    I would like to use Razor's feature not to produce attribute output inside a tag in case when attribute's value is null. So when Razor meets <div class="@var" where @var is null, the output will be mere <div. I've created some Html extension method to write text inside tag. The method takes header text, level (h1..h6), and html attributes as simple object. The code is: public static MvcHtmlString WriteHeader(this HtmlHelper html, string s, int? hLevel = 1, object htmlAttributes = null) { if ((hLevel == null) || (hLevel < 1 || hLevel > 4) || (s.IsNullOrWhiteSpace())) return new MvcHtmlString(""); string cssClass = null, cssId = null, cssStyle = null; if (htmlAttributes != null) { var T = htmlAttributes.GetType(); var propInfo = T.GetProperty("class"); var o = propInfo.GetValue(htmlAttributes); cssClass = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString(); propInfo = T.GetProperty("id"); o = propInfo.GetValue(htmlAttributes); cssId = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString(); propInfo = T.GetProperty("style"); o = propInfo.GetValue(htmlAttributes); cssStyle = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString(); } var hTag = new TagBuilder("h" + hLevel); hTag.MergeAttribute("id", cssId); hTag.MergeAttribute("class", cssClass); hTag.MergeAttribute("style", cssStyle); hTag.InnerHtml = s; return new MvcHtmlString(hTag.ToString()); } I found that in spite of null values for "class" and "style" attributes TagBuilder still puts them as empty strings, like <h1 class="" style="" But for id attribute it surprisingly works, so when id's value is null, there is no id attribute in tag. My question - is such behavior something that should actually happen? How can I achieve absent attributes with null values using TagBuilder? I tried this in VS2013, MVC 5.

    Read the article

  • Easier ASP.NET MVC Routing

    - by Steve Wilkes
    I've recently refactored the way Routes are declared in an ASP.NET MVC application I'm working on, and I wanted to share part of the system I came up with; a really easy way to declare and keep track of ASP.NET MVC Routes, which then allows you to find the name of the Route which has been selected for the current request. Traditional MVC Route Declaration Traditionally, ASP.NET MVC Routes are added to the application's RouteCollection using overloads of the RouteCollection.MapRoute() method; for example, this is the standard way the default Route which matches /controller/action URLs is created: routes.MapRoute(     "Default",     "{controller}/{action}/{id}",     new { controller = "Home", action = "Index", id = UrlParameter.Optional }); The first argument declares that this Route is to be named 'Default', the second specifies the Route's URL pattern, and the third contains the URL pattern segments' default values. To then write a link to a URL which matches the default Route in a View, you can use the HtmlHelper.RouteLink() method, like this: @ this.Html.RouteLink("Default", new { controller = "Orders", action = "Index" }) ...that substitutes 'Orders' into the {controller} segment of the default Route's URL pattern, and 'Index' into the {action} segment. The {Id} segment was declared optional and isn't specified here. That's about the most basic thing you can do with MVC routing, and I already have reservations: I've duplicated the magic string "Default" between the Route declaration and the use of RouteLink(). This isn't likely to cause a problem for the default Route, but once you get to dozens of Routes the duplication is a pain. There's no easy way to get from the RouteLink() method call to the declaration of the Route itself, so getting the names of the Route's URL parameters correct requires some effort. The call to MapRoute() is quite verbose; with dozens of Routes this gets pretty ugly. If at some point during a request I want to find out the name of the Route has been matched.... and I can't. To get around these issues, I wanted to achieve the following: Make declaring a Route very easy, using as little code as possible. Introduce a direct link between where a Route is declared, where the Route is defined and where the Route's name is used, so I can use Visual Studio's Go To Definition to get from a call to RouteLink() to the declaration of the Route I'm using, making it easier to make sure I use the correct URL parameters. Create a way to access the currently-selected Route's name during the execution of a request. My first step was to come up with a quick and easy syntax for declaring Routes. 1 . An Easy Route Declaration Syntax I figured the easiest way of declaring a route was to put all the information in a single string with a special syntax. For example, the default MVC route would be declared like this: "{controller:Home}/{action:Index}/{Id}*" This contains the same information as the regular way of defining a Route, but is far more compact: The default values for each URL segment are specified in a colon-separated section after the segment name The {Id} segment is declared as optional simply by placing a * after it That's the default route - a pretty simple example - so how about this? routes.MapRoute(     "CustomerOrderList",     "Orders/{customerRef}/{pageNo}",     new { controller = "Orders", action = "List", pageNo = UrlParameter.Optional },     new { customerRef = "^[a-zA-Z0-9]+$", pageNo = "^[0-9]+$" }); This maps to the List action on the Orders controller URLs which: Start with the string Orders/ Then have a {customerRef} set of characters and numbers Then optionally a numeric {pageNo}. And again, it’s quite verbose. Here's my alternative: "Orders/{customerRef:^[a-zA-Z0-9]+$}/{pageNo:^[0-9]+$}*->Orders/List" Quite a bit more brief, and again, containing the same information as the regular way of declaring Routes: Regular expression constraints are declared after the colon separator, the same as default values The target controller and action are specified after the -> The {pageNo} is defined as optional by placing a * after it With an appropriate parser that gave me a nice, compact and clear way to declare routes. Next I wanted to have a single place where Routes were declared and accessed. 2. A Central Place to Declare and Access Routes I wanted all my Routes declared in one, dedicated place, which I would also use for Route names when calling RouteLink(). With this in mind I made a single class named Routes with a series of public, constant fields, each one relating to a particular Route. With this done, I figured a good place to actually declare each Route was in an attribute on the field defining the Route’s name; the attribute would parse the Route definition string and make the resulting Route object available as a property. I then made the Routes class examine its own fields during its static setup, and cache all the attribute-created Route objects in an internal Dictionary. Finally I made Routes use that cache to register the Routes when requested, and to access them later when required. So the Routes class declares its named Routes like this: public static class Routes{     [RouteDefinition("Orders/{customerName}->Orders/Index")]     public const string OrdersCustomerIndex = "OrdersCustomerIndex";     [RouteDefinition("Orders/{customerName}/{orderId:^([0-9]+)$}->Orders/Details")]     public const string OrdersDetails = "OrdersDetails";     [RouteDefinition("{controller:Home}*/{action:Index}*")]     public const string Default = "Default"; } ...which are then used like this: @ this.Html.RouteLink(Routes.Default, new { controller = "Orders", action = "Index" }) Now that using Go To Definition on the Routes.Default constant takes me to where the Route is actually defined, it's nice and easy to quickly check on the parameter names when using RouteLink(). Finally, I wanted to be able to access the name of the current Route during a request. 3. Recovering the Route Name The RouteDefinitionAttribute creates a NamedRoute class; a simple derivative of Route, but with a Name property. When the Routes class examines its fields and caches all the defined Routes, it has access to the name of the Route through the name of the field against which it is defined. It was therefore a pretty easy matter to have Routes give NamedRoute its name when it creates its cache of Routes. This means that the Route which is found in RequestContext.RouteData.Route is now a NamedRoute, and I can recover the Route's name during a request. For visibility, I made NamedRoute.ToString() return the Route name and URL pattern, like this: The screenshot is from an example project I’ve made on bitbucket; it contains all the named route classes and an MVC 3 application which demonstrates their use. I’ve found this way of defining and using Routes much tidier than the default MVC system, and you find it useful too

    Read the article

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