我有这段代码来设置我的选择列表的默认值:
public ActionResult Register()
{
IList<Country> countryList = _countryRepository.GetAllCountry();
var registerViewModel = new RegisterViewModel
{
CountryId = 52,
CountryList = new SelectList(countryList, "CountryId", "CountryName", "Select Country")
};
return View(registerViewModel);
}
我在我的观点中有这个,这很有效,将所选国家/地区的值设置为52:
<%: Html.DropDownListFor(model => model.CountryId, Model.CountryList ,"Select Country") %>
但是,当我为此创建编辑器模板时,未选择国家/地区的默认值
所以,我将当前视图更改为:
<%: Html.EditorFor(model => model.CountryId,new { countries = Model.CountryList}) %>
然后我创建我的编辑器模板:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Int64?>" %>
<%= Html.DropDownList(
String.Empty /* */,
(SelectList)ViewData["countries"],
"Select Country"
)
%>
答案 0 :(得分:10)
我通过将控制器中的代码替换为:
来解决这个问题CountryList = new SelectList(countryList, "CountryId", "CountryName",52 /*Default Country Id*/)
如果您有更好的解决方案,请告诉我。我会改变接受的答案。
答案 1 :(得分:1)
将此添加到您的控制器:
ViewData["CountryList"] = new SelectList(_countryRepository.GetAllCountry(), 52);
然后,在“查看”页面上,按如下方式调用下拉列表:
@Html.DropDownList("Countries", ViewData["CountryList"] as SelectList)
答案 2 :(得分:0)
不同的存档方式,这是一种方式
步骤1:将您需要的值设置为默认值。在这里我已经通过了0或2
ViewBag.AssessmentfrezeId = IsUserHavefreeAssessment == false ? 2 : 0;
步骤2:转到Cshtml,如下所示添加所选值。
@Html.DropDownListFor(m => m.TestID, new SelectList(Model.Slots, "Id", "TimeSlot", @ViewBag.AssessmentfrezeId), "--Select--", new { @class = "form-control" })