Understanding how DropDownListFor is working in MVC3

前端 未结 1 1388
盖世英雄少女心
盖世英雄少女心 2021-01-14 19:18

I\'m new to MVC3 and have been working on a small site using EF and \'Code First\'. I\'m trying to do a few things in a view dealing with a drop down list and am wondering w

相关标签:
1条回答
  • 2021-01-14 19:44

    I want a user to be able to select a rule from the dropdownlist, and depending upon which rule was selected, I would like a label on the page to show the rule name (without posting)

    You will need javascript here. jQuery would be perfect for the job. I would start by providing a deterministic id for the dropdown because if you run this view inside a template there could be prefixes added to the id which would ruin our javascript id selectors (see below):

    @Html.DropDownListFor(
        x => x.D1K2N3CARules,
        new SelectList(Model.D1K2N3CARules, "ID", "Rule"),
        new { id = "ruleDdl" }
    )
    

    then provide some container which will receive the selected value:

    <div id="ruleValue" />
    

    and finally in a separate javascript file subscribe for the change event of the dropdown list and update the container with the selected value/text:

    $(function() {
        // subscribe for the change event of the dropdown
        $('#ruleDdl').change(function() {
            // get the selected text from the dropdown
            var selectedText = $(this).find('option:selected').text();
    
            // if you wanted the selected value you could:
            // var selectedValue = $(this).val();
    
            // show the value inside the container
            $('#ruleValue').html(selectedText);
        });
    });
    

    I also need to be able to send the selected rule onto the next page.

    You could put your dropdown inside a form

    @using (Html.BeginForm("NextPage", "Foo"))
    {
        @Html.DropDownListFor(
            x => x.D1K2N3CARules,
            new SelectList(Model.D1K2N3CARules, "ID","Rule")
        )    
        <input type="submit" value="Go to the next page" />
    }
    

    and the NextPage controller action will receive the selected value.

    0 讨论(0)
提交回复
热议问题