Using selected value in @Html.DropDownListFor

2019-06-08 20:27发布

问题:

Hi I'm building application to display reports, I have a set of setting which I would like the user to select, and while he selecting a preview updates. It is strongly typed view:

@model MRS.UI.Models.SettingsModel

@using (Html.BeginForm("Settings", "Report", FormMethod.Post))
{
    <div class="white-box edit-box">
    @Html.DropDownListFor(m => m.range, new SelectList(new List<Object>{new { value = 0, text = "12 hours"}, 
                                                                        new { value = 1, text = "24 hours"},
                                                                        new { value = 2, text = "4 days"},
                                                                        new { value = 3, text = "8 days"},
                                                                        new { value = 4, text = "16 days"},
                                                                        new { value = 5, text = "month"},
                                                                        new { value = 6, text = "quarter"},
                                                                        new { value = 7, text = "year"}
                                                                        },
                                                                        "value",
                                                                        "text",
                                                                        Model.range
                                                        ), new { @class = "select_change" }
                        )

    @Html.TextBoxFor(m => m.title)

    @Html.RadioButtonFor(m => m.layout, 1) <p>Layout 1</p><br />
    @Html.RadioButtonFor(m => m.layout, 2) <p>Layout 2</p><br />
    @Html.RadioButtonFor(m => m.layout, 3) <p>Layout 3</p><br />
    @Html.RadioButtonFor(m => m.layout, 4) <p>Layout 4</p><br />

        <input class="blueButton" type="submit" value="Complete Report"/>
   </div>
}

      <script>
          $('.select_change').change(function () { alert(@Model.range); })
      </script>

After I press "Complete Report" data is saving and then I can use it on different view, but how can I use it on the same view, while is selected. I tried to use JavaScript to display value of range in a form of alert message, but it displays not updated value.

How can I use selected value in @Html.DropDownListFor ?

Many thanks for your help

回答1:

you can't use the value coming from your Model, which is not updated on client side (and the change event happens on client)

You have to do

$(.select_change).change(function() {
   alert($(this).val());//selected value
   alert($(this).find('option:selected').text());//selected option text
});