简体   繁体   中英

mvc razor dropdownlistfor display default from javascript

In my MVC view, I have a country list which is populated with all the countries. This works ok and the user selects different countries & they are displayed ok. I want the ability in Javascript to change that field back to "Select Country", how do I do this?

This is in my view

<div class="form-group">
    @Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { @id = "ddlcountry" })
</div>

This is my javascript

$("#ddlcountry").val(44);    //this works to set the country code to 44
$("#ddlcountry").val("Select Country");    //this does not work to display "Select Country" like the default when you first load the page

How can I have the default of "Select Country" show again?

Your DropDownListFor() method is generating the 'label option' with a null value

<option value="">Select Country</option>

to select that option with jQuery use

$("#ddlcountry").val('');

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