Understanding how DropDownListFor works in MVC3

I am new to MVC3 and work on a small site using EF and "Code First". I'm trying to do a few things in a dropdown view, and I wonder what the best way to do this. I want the user to be able to select a rule from the drop-down list, and depending on which rule was selected, I would like the name of the rule to be displayed on the label on the page (without publishing). I should also be able to post the selected rule to the next page. I haven't added all the required fields to the view yet, because I'm really at a loss about how it should work. How should I try to do this?

I have my model:

public class D1K2N3CARule
{
    public int ID { get; set; }
    [Required]
    public int Name { get; set; }
    [Required]
    public string Rule { get; set; }

    public D1K2N3CARule(int name, string rule)
    {
        Name = name;
        Rule = rule;
    }
    public D1K2N3CARule()
    {
        Name = 0;
        Rule = "";
    }
}

My ViewModel:

public class D1K2N3CARuleViewModel
{
    public string SelectedD1K2N3CARuleId { get; set; }
    public IEnumerable<D1K2N3CARule> D1K2N3CARules { get; set; }
}

My controller:

    public ActionResult Index()
    {
        var model = new D1K2N3CARuleViewModel
        {
            D1K2N3CARules = db.D1K2N3DARules
        };

        return View(model);
    }

and my view:

'@model CellularAutomata.Models.D1K2N3CARuleViewModel

@{
    ViewBag.Title = "Index";
}
<asp:Content id="head" contentplaceholderid="head" runat="server">
<script type="text/javascript">
</script>
</asp:Content>
<h2>Index</h2>

<table>
    <tr>
        <td>
            @Html.DropDownListFor(
                x => x.D1K2N3CARules,
                new SelectList(Model.D1K2N3CARules, "ID","Rule")
            )
        </td>
    </tr>
</table>'
+3
1

, , , , , ( )

javascript . jQuery . , , , id , id JavaScript (. ):

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

, :

<div id="ruleValue" />

, , javascript /:

$(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);
    });
});

.

@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" />
}

NextPage .

+4

Source: https://habr.com/ru/post/1794291/


All Articles