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>

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is the only way I would do this. +1
While I accept you chastising, I have already figured out how to do it and updated the code above.
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.

Comments

0

Try this code for attribute

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.