简体   繁体   中英

How to add Dropdown List default value ID

So in my view I have a drop down list.So I want to add a Id for default selected. This is my controller:

public ActionResult AddRemoveContract()
{
    var companyQuery = db.tblCompanies.OrderBy(c => c.CompanyName);
    ViewData["AllCompany"] = new SelectList(companyQuery, "PKComID", "CompanyName");
    return View();
}

And this is my view:

 @Html.DropDownList("ddlCompany", ViewData["AllCompany"] as SelectList, "--Select Company--", new { @onchange = "getSite(this.value);" }) 

My selected list like this

<select id="ddlCompany" onchange="getSite(this.value);" name="ddlCompany">
    <option value="">--Select Company--</option> // want to add value="0"
    <option value="9">Company A</option>
    <option value="11">Company B</option>
</select>

I want to add value'0' for '--Select Company--'. How to do it?

I would create a Union Query with the second query having the default values that you want. At least then you don't have to try and jump through hoops later on to try and get it added to the HTML select list as its already in the ViewData["AllCompany"] list

The selected value needs to be the value , not the text of the SelectListItem . In other words, your code should be:

@Html.DropDownList("ddlCompany", ViewData["AllCompany"] as SelectList, "", new { @onchange = "getSite(this.value);" })

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