Mr A
Mr A

Reputation: 6778

Working with cascading dropdownlist and textbox in mvc 2

I am trying to hide and unhide the textbox using dropdownlist , so for instance when 0 is selected from drop down, no textbox should appear on the view , but if 1 is selected from dropdownlist , one textbox should appear similarly for selected value 2 , it should show two box , and then I want to pass the selected value and textbox text to http[post] in controller action to carry out some calculation. I can do all this in webforms but I dont know how to acheive this in mvc 2, I can pass the value from view to controller using Form collection but how will I pass the dropdownlist value. Any examples or suggestions will be appreciated.

Upvotes: 0

Views: 1682

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

There are many ways to implement this so let's take one example using javascript to manage the input fields based on the selected value of the dropdown list.

As always start with a view model:

public class MyViewModel
{
    public string[] Values { get; set; }
    public int SelectedItem { get; set; }
    public IEnumerable<SelectListItem> Items
    {
        get
        {
            return Enumerable.Range(0, 4).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = x + " Item(s)"
            });
        }
    }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            SelectedItem = 2,
            Values = new[] { "", "" }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // Here you will get the model properly initialized
        return View(model);
    }
}

and finally the view:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<AppName.Models.MyViewModel>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title>Index</title>
    <script type="text/javascript" src="<%: Url.Content("~/scripts/jquery-1.5.1.js") %>"></script>
    <script type="text/javascript">
        $(function () {
            $('#SelectedItem').change(function () {
                var count = parseInt($(this).val(), 10);
                if (count == 0) {
                    $('#values').html('');
                    return;
                }

                for (var i = 0; i < count; i++) {
                    var item = $(':text[name="Values[' + i + ']"]');
                    if (item.length < 1) {
                        $('#values').append(
                            $('<div/>').html(
                                $('<input/>', {
                                    type: 'text',
                                    'data-index': i,
                                    name: 'Values[' + i + ']',
                                    value: ''
                                })
                            )
                        );
                    }
                }

                $('#values :text').each(function (index, element) {
                    if (index >= count) {
                        $(element).parent('div').remove();
                    }
                });

            });
        });
    </script>
</head>
<body>
    <div>
        <% using (Html.BeginForm()) { %>
            <%= Html.DropDownListFor(
                x => x.SelectedItem, 
                new SelectList(Model.Items, "Value", "Text")
            ) %>

            <div id="values">
                <% for (int i = 0; i < Model.Values.Length; i++) { %>
                    <div>
                        <%= Html.EditorFor(x => x.Values[i]) %>
                    </div>
                <% } %>
            </div>

            <input type="submit" value="OK" />
        <% } %>
    </div>
</body>
</html>

Upvotes: 1

Tassadaque
Tassadaque

Reputation: 8199

you need to write some javascript on click event of the dropdown and for passing the resulted array you can get some initial idea from here

Upvotes: 1

Related Questions