简体   繁体   中英

MVC Razor drop down list default value is not triggering onchange event

I have a drop down list in c# MVC Razor application that is populated via enum data model object.My issue comes into play when the user selects the drop down the default value is the first value from the model and when it is selected the onchange event is not being triggered. Please see code below:

.net core mvc razor view

            <tr>
                <td>
                    <a id="GenderLnk" href="#">Click Here to Update</a><br>
                    <div id="GenderDiv" style="display:none;">
                        @using (Html.BeginForm("UpdateGender", "Home", FormMethod.Post))
                        {
                            @Html.DropDownListFor(m => m.StudentGender, new SelectList(Enum.GetValues(typeof(Gender))), new { @class = "show", onchange = "this.form.submit();" })
                        }
                    </div>
                </td>
            </tr>

Here is the model property

    public Gender StudentGender { get; set; }

    public enum Gender
    {
        Female,
        Male,
        [Display(Name ="Not Applicable")]
        NotApplicable,
        Transgender

    }

这是下拉列表的屏幕截图,其中包含 Dilan 建议的代码。可以看到,仍然是女性是默认的

The reason for not triggering the "onChange" function is, it technically does not change any value in the form if user selected the default value in the first attempt. What you can do is provide a value like "please select" as the default value and let the user choose a value in the list.

@Html.DropDownListFor(m => m.StudentGender, new SelectList(Enum.GetValues(typeof(Gender))), "-- Please Select -- ", new { @class = "show", onchange = "this.form.submit();" })

May be you can use this question + answer into consideration as well. Hope this helps.

Get a default NULL value from DropDownList in ASP.NET MVC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM