3

Trying to load a dropdownlist from an array of Countries:

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>

This is the output:

<option af?"selected="\&quot;selected\&quot;&quot;:&quot;&quot;)" (us="=" value="AF">Afghanistan</option>

What am I doing wrong and how can I fix it? I've also tried this but get an exception:

@Html.DropDownList("BusinessCountry", new SelectList(Countries, "CountryCode", "CountryName", @ViewBag.part.BusinessCountry), Countries)

Already figured out how to do it with the code I have:

<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>
MB34
  • 4,210
  • 12
  • 59
  • 110

3 Answers3

6

Mixing a lot of code in the view is a wrong way to do this. Also usage of ViewBag/ViewData to transfer data like this between action methods and views, makes your code ugly. You should consider a ViewModel to transfer the data from action method to view.

Assuming your view is to create a Company Details, Have a view model like this

public class CompanyViewModel
{
  public string Name { set;get;}
  public IEnumerable<SelectListItem> Countries { set;get;}
  public int SelectedCountry { set;get;}

  CompanyViewModel()
  {
    Countries=new List<SelectListItem>();
  }
}

Now in your GET Action method, you will fill the data to the Countries collection of the viewModel object and send that to the 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);
}

Now in your strongly typed view,

@model CompanyViewModel
@using(Html.Beginform())
{
   @Html.DropDownListFor(x => x.SelectedCountry,
                   new SelectList(Model.Countries,"Value","Text"), "Select..")
   <input type="submit" />

}

Now in your HTTPPost method, you will get the Selected country id by accessing the SelectecCountry Properties value of the Model posted

[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);
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

I use dropdown list like this:

In Controller:

ViewBag.CompanyId = New SelectList(db.Companies, "CompanyId", "Name", blog.CompanyId)

In View:

<div class="editor-field">
    @Html.DropDownList("CompanyId", String.Empty)
    @Html.ValidationMessageFor(Function(model) model.CompanyId)
</div>

Note: This is VB.

user1477388
  • 20,790
  • 32
  • 144
  • 264
0

Try this code for attribute

@((ViewBag.BusinessCountry == @c.CountryCode) ? "selected='selected'" : "")
STO
  • 10,390
  • 8
  • 32
  • 32