Populating a Razor Dropdownlist from a List<Object> in MVC

Populating a razor dropdownlist from a List object in MVC

You can separate out your business logic into a viewmodel, so your view has cleaner separation.

First create a viewmodel to store the Id the user will select along with a list of items that will appear in the DropDown.

ViewModel:

public class UserRoleViewModel
{
// Display Attribute will appear in the Html.LabelFor
[Display(Name = "User Role")]
public int SelectedUserRoleId { get; set; }
public IEnumerable<SelectListItem> UserRoles { get; set; }
}

References:

  • DisplayAttribute

Inside the controller create a method to get your UserRole list and transform it into the form that will be presented in the view.

Controller:

private IEnumerable<SelectListItem> GetRoles()
{
var dbUserRoles = new DbUserRoles();
var roles = dbUserRoles
.GetRoles()
.Select(x =>
new SelectListItem
{
Value = x.UserRoleId.ToString(),
Text = x.UserRole
});

return new SelectList(roles, "Value", "Text");
}

public ActionResult AddNewUser()
{
var model = new UserRoleViewModel
{
UserRoles = GetRoles()
};
return View(model);
}

References:

  • SelectListItem
  • SelectList Constructor (IEnumerable, String, String)

Now that the viewmodel is created the presentation logic is simplified

View:

@model UserRoleViewModel

@Html.LabelFor(m => m.SelectedUserRoleId)
@Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)

References:

  • LabelExtensions.LabelFor
  • SelectExtensions.DropDownListFor

This will produce:

<label for="SelectedUserRoleId">User Role</label>
<select id="SelectedUserRoleId" name="SelectedUserRoleId">
<option value="1">First Role</option>
<option value="2">Second Role</option>
<option value="3">Etc...</option>
</select>

Populating razor DropDownList from view model

I think you are complicating yourself.

Just use this model:

public class ComponentTypeModel
{
public int? SelectedComp {get; set;}
public SelectList DDLCompTypes {get; set;}
}

Then in your controller:

var model = new ComponentTypeModel();
model.DDLCompTypes = new SelectList(theComponentTypes, "Id","Name");

//If you need to set some value in the DropDownValue (for instance in the Edit view) you do:
model.DDLCompTypes = new SelectList(theComponentTypes, "Id","Name", model.SelectedComp);

Then in your View:

@Html.DropDownFor(x => x.SelectedComp, Model.DDLCompTypes, "Select a component type" )

Populate Razor DropDownList with Object passed from Controller C#

Let's take it one thing a time.

What is the format of your data?

It is an object like this:

{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
"AMD": "Armenian Dram",
"ANG": "Netherlands Antillean Guilder"
}

So we have a bag with key/value pairs, the key is the currency's code and the value is the currency's name.

How can we deserialize this?

As simple as below:

var res = JsonConvert.Deserialize<Dictionary<string,string>>(json_data);

What do we want to show in our View?

At least a dropdown with all the available currencies. If you need more data to show, you have to add the extra properties in the Model and initialize them correspondingly, when you create the model.

How can we achieve this?

@model CurrencyModel

<div class="form-group">
<label for="fromC">From Currency</label>
<div class="col-md-6">
@Html.DropDownList("Currencies", CurrencyModel.Currencies)
</div>
</div>

What do we need?

A model with at least one property of type IEnumerable<SelectListItem> called Currencies:

public class CurrencyModel
{
public IEnumerable<SelectListItem> Currencies { get; set; }
}

Who will create this model ?

This responsibility belongs to the controller.

public class WebAPIController : Controller
{
public ActionResult Converter()
{
var currencies = new CurrenciesRepository.GetAll();

var currencyModel = new CurrencyModel
{
Currencies =
currencies.Select(currency => new SelectListItem {
Text = currency.Value,
Value = currency.Key});
}
return View("Index", currencyModel);
}
}

What it is needed now is to create one new class the CurrenciesRepository

public class CurrenciesRepository
{
string _url = "http://openexchangerates.org/api/currencies.json";

public IDictionary<string, string> GetAll()
{
using (var webClient = new WebClient())
{
var data = webClient.DownloadString(_url);
var currencies= JsonConvert.DeserializeObject<Dictionary<string,string>>(data);

return currencies;
}
}
}

populating dropdown menu from database in ASP.NET MVC

If the drop down menu options are in a database, why not add a list to your model, populate that list in your GET ActionMethod and then render it using the DropdownListFor helper tag.
For example...

public class Appointment
{
public IEnumerable<SelectListItem> Clinic {get; set;}
//You should add this for every dropdown menu you intend to put in the list.
//I am guessing you already have a model like this as this was not in the question
}

public class Clinic
{
public int ClinicId {get; set;}
public string ClinicName {get; set;}
}

In the controller, you can then query the database for the options

    public ActionResult Create()
{
var Clinic = context.Clinic.ToList();
var model = new Appointments()
{
Clinic = Clinic.Select(x => new SelectListItem
{
Value = x.ClinicId.ToString(),
Text = x.ClinicName
}
}
return View(model);
}

Like before, you would have to do this for all the fields. If you are worried about the numerous roundtrip to the database to get the values, do some research about Z.EntityFrameWork nuget pakages that lets you run batch SQL statements so you can get all three results with one database round trip.

Then in the view, you can do this...

@Html.DropDownListFor(m => m.ClinicId, Model.Clinic, "Select Clinic", new { @class = "form-control", id = "clinic" })


Related Topics



Leave a reply



Submit