views:

267

answers:

3

I'm populating a dropdownlist in c# asp.net-MVC from a SQL table using Linq2Sql. I'd like for the user to be able to enter something that isn't in the list into the drop down and have it add to the table. Is this possible?

+4  A: 

Sounds like you need to add a radio button labeled "Other". When the user clicks the radio button a text box would appear that allows the user to input a new value that you can save to your DB and display in the drop down.

EDIT:
Quick snippet to enable the control using JavaScript:

    <script language="javascript" type="text/javascript">
       function radioclicked() {
        textObj = document.getElementById('<NAME OF TEXT BOX');
        textObj.disabled = false;
        }     
    </script>

You can use a check box instead of a radio button so that the enabled property can be toggled.

To completely hide the text box then you will have to look into jQuery/Ajax.

Miyagi Coder
I'm brand new to MVC and web apps, my experience is in WinForms. How can I make a text box appear when a radio button is clicked?
RememberME
I've never used jQuery before. Is that what would be needed?
RememberME
You can use jQuery if you want to control the visibility. Or you can use JavaScript if you want to simply enable disable the control.
Miyagi Coder
A: 

Also a combobox will allow a user to enter a value in addition to picking from a list.

jstell
A: 

My MVC is not so so, but I assume this still applies as MVC is just model view controller. What if you throw a drop down on your form visible=true, and a textbox on your form visible =false.

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
    onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" Visible="False"></asp:TextBox>

Fill your drop down:

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            List<int> s = Enumerable.Range(1, 10).ToList();
            DropDownList1.DataSource = s;
            DropDownList1.DataBind();

            DropDownList1.Items.Add("Other");
        }
    }

Add an event to handle if someone selects other. If they do make the textbox visible:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    switch (this.DropDownList1.SelectedItem.Text)
        {
        case "Other":
            this.TextBox1.Visible=true;
            break;
        default:
            this.TextBox1.Visible=false;
            break;
        }
}

Now you can enter your value and re-store back to the db.

JonH