MVC3从数组中创建下拉列表

3
尝试从国家数组加载下拉列表:
```html

尝试从国家数组加载下拉列表:

```
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="\&quot;selected\&quot;&quot;:&quot;&quot;)" (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>
3个回答

6
在视图中混合大量代码是错误的。使用ViewBag/ViewData在控制器方法和视图之间传递数据也会让您的代码变得丑陋。您应该考虑使用ViewModel将数据从控制器方法传递到视图。 假设您的视图是用于创建公司详细信息,请像这样拥有一个视图模型。
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操作方法中,您将向viewModel对象的Countries集合填充数据并将其发送到视图。
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
这是我唯一会做的方法。+1 - Gromer
虽然我接受你的批评,但是我已经想出了如何做,并更新了上面的代码。 - MB34

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。

0

尝试使用此代码来获取属性

@((ViewBag.BusinessCountry == @c.CountryCode) ? "selected='selected'" : "")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接