Ethan Schofer
Ethan Schofer

Reputation: 1848

ASP .Net MVC DropDownList bound to nullable field

I have a dropdownlist. Its not required, so that backing field is nullable. But, when the form loads, the dropdownlist seems to be setting the selected value to the first id (first sequentially).

I build the select list items like this:

var servers = await Context.Servers.OrderBy(s => s.Name).ToListAsync();
servers.Insert(0, new Models.Server() { Id = Guid.Empty, Name = "SELECT ONE" });
return servers.Select(t => new SelectListItem()
{
    Selected = t.Id == Guid.Empty ? true : false,
    Text = t.Name,
    Value = t.Id.ToString()
}); 

And I render it like this:

@Html.DropDownListFor(m => m.ProductionEnvironment_ServerId, Model.ProductionEnvironment_Servers)

The first sequential Guid in the ID field is selected if ServerId is null. If I make ServerId non-nullable, the drop down becomres required, which it should not be.

Upvotes: 0

Views: 1355

Answers (1)

Shyju
Shyju

Reputation: 218942

In your GET action method, Set your view model'sProductionEnvironment_ServerId property value to the one you want to be selected when the dropdown is rendered.

public ActionResult Edit()
{
  var vm = new YourViewModel(int id);
  vm.ProductionEnvironment_Servers = servers.Select(s => new SelectListItem
            {
                Value = s.Id.ToString(),
                Text = s.Name
            });

  //Set the value you want to be selected.
 Guid guidWhichShouldBeSelected = GetSelectedGuidHereFromSomeWhere(id);

 vm.ProductionEnvironment_ServerId = guidWhichShouldBeSelected;
 return View(vm);
}

Also, in the razor view, you can use this override of the helper method to add a "Select" option to the option list. You don't need to add one from server side.

@Html.DropDownListFor(m => m.ProductionEnvironment_ServerId, 
                                            Model.ProductionEnvironment_Servers,"Select")

This will add "Select" option as the first option.

When you submit the form, In your HttpPost action method, check the value of ProductionEnvironment_ServerId property of the posted model. You will get the selected Item's value (a Guid) or null if they select the first "Select" option.

[HttpPost]
public ActionResult Edit(YourViewModel model)
{
  //check model.ProductionEnvironment_ServerId 
  // to do : Save and Redirect
}

Upvotes: 1

Related Questions