尝试从一系列国家/地区加载下拉列表:
Country[] Countries = ViewBag.mps.GetCountryList(ViewBag.LogonTicket, ViewBag.PID);
/* Country object defined as, returned from WCF webservice call above:
<xs:complexType name="Country">
<xs:sequence>
<xs:element minOccurs="0" name="CountryName" nillable="true" type="xs:string" />
<xs:element minOccurs="0" name="CountryCode" nillable="true" type="xs:string" />
</xs:sequence>
</xs:complexType>
*/
<select id="BusinessCountry" name="BusinessCountry" class="validate[required]" parentTab="tab4" style="width:160px;">
@{
foreach(Country c in Countries) {
<option value="@c.CountryCode" (@ViewBag.BusinessCountry == @c.CountryCode?"selected=\"selected\"":"") >@c.CountryName</option>
}
}
</select>
这是输出:
<option af?"selected="\"selected\"":"")" (us="=" value="AF">Afghanistan</option>
我做错了什么,我该如何解决?我也尝试了这个,但得到一个例外:
@Html.DropDownList("BusinessCountry", new SelectList(Countries, "CountryCode", "CountryName", @ViewBag.part.BusinessCountry), Countries)
<select id="BusinessCountry" name="BusinessCountry" class="validate[required]" parentTab="tab4" style="width: 160px;">
@foreach(Country c in Countries) {
string sel = (ViewBag.part.BusinessCountry == c.CountryCode?"selected=\"selected\"":"");
<option value="@c.CountryCode" @sel >@c.CountryName</option>
}
</select>
答案 0 :(得分:5)
在视图中混合使用大量代码是一种错误的方法。使用ViewBag
/ ViewData
在动作方法和视图之间传输此类数据也会使代码变得丑陋。您应该考虑使用ViewModel将数据从action方法传输到view。
假设您的观点是创建公司详细信息,请使用此类视图模型
public class CompanyViewModel
{
public string Name { set;get;}
public IEnumerable<SelectListItem> Countries { set;get;}
public int SelectedCountry { set;get;}
CompanyViewModel()
{
Countries=new List<SelectListItem>();
}
}
现在,在GET
Action方法中,您将数据填充到viewModel对象的Countries
集合中,并将其发送到View。
public ActionResult Create()
{
CompanyViewModel vm=new CompanyViewModel();
// The below line is hard coded for demo. you may replace
// this with loading data from your Data access layer/ Existing array
vm.Countries= new[]
{
new SelectListItem { Value = "1", Text = "United States" },
new SelectListItem { Value = "2", Text = "Canada" },
new SelectListItem { Value = "3", Text = "Australia" }
};
return View(vm);
}
现在在强类型视图中,
@model CompanyViewModel
@using(Html.Beginform())
{
@Html.DropDownListFor(x => x.SelectedCountry,
new SelectList(Model.Countries,"Value","Text"), "Select..")
<input type="submit" />
}
现在,在您的HTTPPost
方法中,您将通过访问已发布模型的SelectecCountry
属性值来获取所选国家/地区ID
[HttpPost]
public ActionResult Create(CompanyViewModel model)
{
if(ModelState.IsValid)
{
//check for model.SelectedCountry property value here
//Save and Redirect
}
//Reload countries here
return View(model);
}
答案 1 :(得分:0)
我使用这样的下拉列表:
在控制器中:
ViewBag.CompanyId = New SelectList(db.Companies, "CompanyId", "Name", blog.CompanyId)
在视图中:
<div class="editor-field">
@Html.DropDownList("CompanyId", String.Empty)
@Html.ValidationMessageFor(Function(model) model.CompanyId)
</div>
注意:这是VB。
答案 2 :(得分:0)
尝试使用此代码进行属性
@((ViewBag.BusinessCountry == @c.CountryCode) ? "selected='selected'" : "")