Preview 3 - Html.ListBox and Html.DropDownList - Please Add Prompt Support Back

Hi,

Not sure if this is the appropriate feedback venue but I'm missing the ability to add a "prompt" to select tags - e.g., add a prompt "choose one..." as first option element BEFORE actual options are displayed.

Preview 2 / April 16 2008 release had the following in SelectBuilder.cs.  I modified this routine to add the "prompt" option BEFORE the options loop and it worked well.   I don't see any support for the "prompt" htmlattribute in Preview 3 source release.

                //see if one of the settings is a prompt
                if (htmlAttributes.ContainsKey("prompt")) {
                    string prompt = TagBuilder.CreateTag(HtmlTagType.Option, "", new RouteValueDictionary(new { text = htmlAttributes["prompt"].ToString(), value = "" }));
                    sbOptions.Append(prompt);
                    htmlAttributes.Remove("prompt");
 

 

Thanks!

 

 

Shawn

0
shware
6/2/2008 3:03:07 PM
asp.net.mvc 4300 articles. 0 followers. Follow

6 Replies
890 Views

Similar Articles

[PageSpeed] 41

Hey Shawn,

I agree, I really liked that feature. If you are intereted, I have implemented the workaround below:

 

// <%= Html.DropDownList("promptList", new PromptSelectList(items, "ValueField", "TextField", selectedValue) { Prompt = "Please select" }) %>

public class PromptSelectList : SelectList
{
public string Prompt { get; set; }

public override IList<ListItem> GetListItems()
{
IList<ListItem> items = base.GetListItems();

if (!String.IsNullOrEmpty(Prompt))
{
items.Insert(0, new ListItem() { Text = Prompt, Value = String.Empty });
}

return items;
}

public PromptSelectList(SelectList selectList)
: this(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectList.SelectedValue)
{
}

public PromptSelectList(SelectList selectList, string prompt)
: this(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectList.SelectedValue)
{
this.Prompt = prompt;
}

public PromptSelectList(IEnumerable items)
: base(items)
{
}

public PromptSelectList(IEnumerable items, object selectedValue)
: base(items, selectedValue)
{
}

public PromptSelectList(IEnumerable items, string dataValueField, string dataTextField)
: base(items, dataValueField, dataTextField)
{
}

public PromptSelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)
: base(items, dataValueField, dataTextField, selectedValue)
{
}
}
 

Cheers,

Richard Szalay

0
richard
6/5/2008 10:07:22 AM

 Hi Shawn, I did it with an extension method on IQueryable<T>, so if you're using LINQ-to-SQL (or anything that returns IQueryable<T>) you can write something like this:

 

var items = myDataContext.Countries.WithSelectItem(c => c.Name);
You now have a new country added to the beginning of the list with c.Name = "<select>". Here's the extension method:
 
 
        public static IQueryable WithSelectItem(this IQueryable items, Expressionstring>> propertyExpression) 
            where T : new()
        {
            if (propertyExpression.Body.NodeType != ExpressionType.MemberAccess)
            {
                throw new ArgumentException(expression_not_property);
            }
            
            var memberExpression = propertyExpression.Body as MemberExpression;
            var property = memberExpression.Member as PropertyInfo;
            if (property == null)
            {
                throw new ArgumentException(expression_not_property);
            }

            var selectItem = new T();
            property.SetValue(selectItem, "&lt;select>", null);

            var selectItems = new List { selectItem }.AsQueryable();
            return selectItems.Union(items);
        }
  
  
0
mikehadlow
6/5/2008 10:29:40 AM

Hi everyone,

This is a very common feature request and we're hoping to add it to a future preview of ASP.NET MVC. Thanks for the feedback and suggestions!

Thanks,

Eilon


Blog: http://weblogs.asp.net/LeftSlipper/
0
Eilon
6/6/2008 12:09:34 AM

 Hi,

 
Thanks for the replies and suggestions.  I came up with the following in HtmlHelper.Select.cs:

 
        private string SelectInternal(string name, MultiSelectList selectList, bool usedViewData, bool allowMultiple, IDictionary<string, object> htmlAttributes) {
            if (String.IsNullOrEmpty(name)) {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");
            }
            if (selectList == null) {
                throw new ArgumentNullException("selectList");
            }

            // If we haven't already used ViewData to get the entire list of items then we need to
            // use the ViewData-supplied value before using the parameter-supplied value.
            if (!usedViewData) {
                object defaultValue;
                if (ViewData.TryGetValue(name, out defaultValue)) {
                    selectList = new MultiSelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField,
                        (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue });
                }
            }

            // Convert each ListItem to an <option> tag
            StringBuilder listItemBuilder = new StringBuilder();

            // SHWARE - add support for prompt to preview 3
            if (htmlAttributes.ContainsKey("prompt"))
            {
                listItemBuilder.AppendLine("<option value=\"\">" + HttpUtility.HtmlEncode(htmlAttributes["prompt"].ToString()));
            }
            // END SHWARE

            foreach (ListItem item in selectList.GetListItems()) {
                listItemBuilder.AppendLine(ListItemToOption(item));
            }

            TagBuilder builder = new TagBuilder("select") {
                Attributes = ToStringDictionary(htmlAttributes),
                InnerHtml = listItemBuilder.ToString()
            };
            TryAddValue(builder.Attributes, "name", name);
            TryAddValue(builder.Attributes, "id", name);
            if (allowMultiple) {
                TryAddValue(builder.Attributes, "multiple", "multiple");
            }
            return builder.ToString();
        }
Kinda like how Preview 2 / April 16 release handled prompts. I love having the source available. Yes Hope MVC is released with source.  Having the ability to tweak things is one of it's nicest features so far. Big Smile

 

Thanks again,

 

Shawn

 

0
shware
6/6/2008 12:48:54 PM

Here's a pretty simple solution that doesn't require modifying the source code. It basically just creates a list of the object in question and then unions that with the linq query.

Dim oStatePrompt As New RefState()
        oStatePrompt.StateCode = "Select..."
        oStatePrompt.StateId = -1
        
        Dim oStatePromptList As New List(Of RefState)()
        oStatePromptList.Add(oStatePrompt)



<%=Html.DropDownList("FirstState", New SelectList(oStatePromptList.Union(edc.RefStates.Where(Function(_s) _s.Deleted = False)), "StateId", "StateCode", ViewData.Model.StateId), oDDStyle)%>
  
0
VinBrown
6/17/2008 5:18:39 PM

All excellent solutions, but for someone who's looking for something easy-peasy

List<Class> instance = _classSvc.GetClassCollection().ToList();

instance.Insert(0,new Class{ Code="Select", Id=0}); // assuming your class is like this  public int Id { get; set; }  public string Code { get; set; }

ViewData["VIEWDATA"] = new SelectList(class, "Id", "Code");

 

// <%=Html.DropDownList("ForeignKeyId", (SelectList)ViewData["VIEWDATA"])%>

 

Hope this helps!

0
Pikesville
4/17/2009 1:14:51 AM
Reply:

Similar Artilces:

Installation Fails: MVC Preview 3 requires the .NET Framework version 3.5
The problem is... I already have it installed.  So I tried uninstalling it, then re-installing it.  Then I tried the MVC preview with the same results.  Then I installed the .NET Framework 3.5 SP1 and tried installing the MVC preview with the same results. Any ideas? By the way, I have Vista Ultimate, VS 2005 Pro & VS 2008 Standard installed along with the Silverlight 2 Beta 2....

Firefox 3 is going to be cool, but doesn't support themes and other plug-ins / add-ons I need right now, so going to revert back to version 2
Name: James Gagne Email: jgagneats-tdotcom Product: Firefox Release Candidate Summary: Firefox 3 is going to be cool, but doesn't support themes and other plug-ins / add-ons I need right now, so going to revert back to version 2 Comments: I like how the recent search queries appear in the address bar and I didn't get enough time to really play around with it to see any other enhancements, but I'm sure it'll be great. Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008051206 Firefox/3.0 From URL: http://hendrix.mozilla.org/ ...

MVC is only for .Net 3.5? Is it not available for .Net 2.0?
Hello. I´m new to MVC and I want to try it.. My fist question is: MVC is only for .Net 3.5? Is it not available for .Net 2.0?Thanks!  You could get it to run on 2.0: http://www.hanselman.com/blog/DeployingASPNETMVCOnASPNET20.aspx, but you would be better advised to get 3.5 SP1.  It is free, after all.  So is Visual Web Developer Express, so you can play with it. Regards Mike [MVP - ASP/ASP.NET]My site ASP.NET MVC distributed assemblies reference System.Core.dll assembly from .NET FW 3.5 so you need .NET FW 3.5 to run ASP.NET MVC.Don't forget to click &qu...

how to revert back to .net 2.0 from .net 3.5?
I have developed a small app in VS2008 and now realize that the hosting company I deal with only has .net 2.0   how can I revert the site back to 2.0? Change the target .NET Framework (from Website property pages/Build section) to .NET 2.0. If you have used 3.5 specific features (both language-specific and .NET Framework classes), you have to change the code too.Mark replies as answers if they helped you solve the problem....

ajax 3.5 extensions preview and .NET 3.5
I'm a little bit confused.On one hand you say the AJAX framework is included in .NET 3.5. On the other hand there's an ajax extensions preview which "provides new functionality being added to ASP.NET 3.5 and ADO.NET in 2008." Is the latter like an addon to the .NET 3.5 built-in framework? Out of a developer perspective I would like to know if it is "safe" to develop with the 3.5 extension preview.. and if at any state its functionality is added to the .NET framework. Do I need to install the 3.5 extension preview on my host running IIS, too? Or i...

WPF .xaml .net 3.5 support in PowerDesigner 3.5
When we will have support to reverse engineer using windows presentation foundation? What would you want the result of that to be? A UML class diagram? An XML model? -- Paul Horan[Sybase] paulhoran.pbdjmagazine.com <Juliano> wrote in message news:49b9c630.592b.1681692777@sybase.com... > When we will have support to reverse engineer using windows > presentation foundation? The same that any tools like Enterprise Architech from Sparx, one UML representation, if I have interfaces in my xaml.vb or xaml.cs, I want see in my diagram after a reverse engenieer, ...

Problems with upgrading existing preview 2 MVC application to preview 3
hey, Im trying to upgrade an application i have developed in ASP.NET MVC preview 2. When downloading the preview 3 release i read the Preview3 Readme.doc and made the changes. Unfortunately the application is not working. After successfully building the application i get the following error: Server Error in '/' Application. Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Mess...

I installed .net 2.0 but there is .net 3.0 in the add or remove programs list as well, why
Hi, installed .net 2.0 "i know thats what iam running" but recently i found .net 3.0 as well when browsing the add or remove programs list. .net 2.0 is in the list as well but i dont remember a day i installed .net 3.0. The questions are how did it install. What version of .net is running on my system then. --------------------------------------------------No Project Too Eazy.-------------------------------------------------- >>The questions are how did it install.  Are you running Vista?  (.net 3.0 comes with Vista) >>What&...

Reference in .Net
This is a multi-part message in MIME format. ------=_NextPart_000_0023_01C38440.4B0DE100 Content-Type: multipart/alternative; boundary="----=_NextPart_001_0024_01C38440.4B0DE100" ------=_NextPart_001_0024_01C38440.4B0DE100 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi! We have a server-sdk supporting both version 7 and 8 of SQL Anywhere. = The sdk is in use=20 by several of our customers. Now I'm going to add support for version 9. And I'm wondering what = driver I should set reference to in...

Support for dw.NET 2.5 in VS 2008, .NET framework 3.5 and Oracle 10.2g
Hi, I intend to use the datawindow.NET 2.5 in VS 2008 (.NET framework 3.5) using a Oracle 10.2g database as a backend and later using Oracle 11g as backend. Can someone please let me know if the product is supported in the environments mentioned. All help will be highly appreciated and many thanks in advance. Regards Hasan Kasamali On Nov 24, 3:06=A0am, Hasan Kasamali wrote: > Hi, > > I intend to use the datawindow.NET 2.5 in VS 2008 (.NET > framework 3.5) using a Oracle 10.2g database as a backend > and later using Oracle 11g as backend. > > Can ...

Can I switch from .Net 3.5 to .Net 3
After finishing the website that I built in VS 2008 and has AjaxControlToolkit controls. I was informed by the network admin that the server has .Net 3 and that we can't install .Net 3.5. I tried to change the application settings from Property Page --> Build node, and then select .Net Framework 3.0 from Target Framework Dropdownlist, and then click OK BUT then I can't run my application I get error message and the     <asp:ScriptManager ID="ScriptManager1" runat="server" />   is unknown even when I try ...

Hosting provider only supports .net 2.0 but I developed site in .net 3.5 with Visual Studios '08
I developed a simple site in VS '08 & it's not working on the www after uploading to my hosting provider.  I called technical support & they told me that they only support .net version 2.0 & that my site wasn't displaying b/c I had developed it with .net version 3.5. I understand that the newest versions are built on the previous...  But how do I develop this correctly so that it will work on the www? I don't need to worry about converting what I've already created.  It's just a test page displaying a picture so I can start from scrat...

Hosting provider only supports .net 2.0 but I developed site in .net 3.5 with Visual Studios '08
Is there a way to develop in .net 2.0? My hosting provider only supports .net version 2.0 & I'm using VS '08....  & is creating a site with .net 3.5? I have several .net versions installed, but how do I know, how can I use .net 2.0? Right click on the project, choose Properties and specify 2.0 as a target framework.Thanks------------------------------------------------------------This posting is provided "AS IS" with no warranties, and confers no rights. That was easy...  THANKS!  ...

Installed Extensions 3.5 Preview
Hello everyone!I'm new to ASP.NET and have decided to jump straight in with the MVC framework as I've used MVC's on PHP for a while and love the concept!However, I'm having a few problems getting started.I have installed the Extensions 3.5 Preview and Visual Web Developer Express 2008 but the MVC templates are not available and the 3.6.0.0 extensions (of which the MVC objects are apart) do not appear in the object browser Any help would be greatly appreciated.Regards,Jason (aka Freakish_05)  Hi again everyone.  It turns out my problem was that because I am using ...

[PATCH 1/3] buildperl.pl: add patches to support gcc 3.x and 4.x when compiling Perl 5.6.x
--- cpan/Devel-PPPort/devel/buildperl.pl | 144 ++++++++++++++++++++++++++++++++++ 1 files changed, 144 insertions(+), 0 deletions(-) diff --git a/cpan/Devel-PPPort/devel/buildperl.pl b/cpan/Devel-PPPort/devel/buildperl.pl index 49b7fbb..529c999 100644 --- a/cpan/Devel-PPPort/devel/buildperl.pl +++ b/cpan/Devel-PPPort/devel/buildperl.pl @@ -132,6 +132,32 @@ my @patch = ( [ \&patch_sysv ], ], }, + { + perl => [ + '5.6.0', + ], + subs => [ + [ \&patch_gcc_56 ], + [ \...

Web resources about - Preview 3 - Html.ListBox and Html.DropDownList - Please Add Prompt Support Back - asp.net.mvc

Tag Synonyms - Stack Overflow
Q&A for professional and enthusiast programmers

Accidental entities - what about the UI?
This post is a follow-up to my previous blog post " Accidental entities - you don't need that identity ". In that post, we followed a consultant ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Air Astana - Join Now
Thank you for considering membership of Nomad Club – Kazakhstan’s first Frequent Flyer Program. You could soon be on your way to earning free ...

Languages -> C# Articles, Tutorials, Examples: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Blog - Avisra
Avisra Web Development Home Blog Services Contact The Blog Latest Module Builder: How can we make it better? Sitefinity by Chris on July 2, 2013 ...

Online Booking Tool Support
This Online Booking Tool Support page might help you as you navigate through the process of booking travel through your OBT provided by CWT. ...

@Html and beyond
... ); } return string .Format( “{0}{1}” , me.Member.Name, id); } The Html building methods are quite simple. Building a dropdownlist for a ...

Top Ranked Articles
Top Ranked Articles - Free source code and tutorials for Software developers and Architects.; Updated: 23 Feb 2013

Unit Testing DateTime.Now Without Isolation
public virtual void SeedWithYearsSince(DropDownList list, int year){ for (int index = year; index

Resources last updated: 12/23/2015 8:15:00 PM