views:

94

answers:

3

I have the following code-

View-

<% Html.BeginForm(); %>
    <div>
<%= Html.DropDownList("DropDownSelectList", new SelectList( Model.DropDownSelectList, "Value", "Text"))%>

Controller-

public ActionResult Admin(string apiKey, string userId)
{
    ChallengesAdminViewModel vm = new ChallengesAdminViewModel();
    vm.ApiKey = apiKey;
    vm.UserId = userId;
    vm.DropDownSelectList = new List<SelectListItem>();
    vm.DropDownSelectList.Add(listItem1);
    vm.DropDownSelectList.Add(listItem2);
    vm.DropDownSelectList.Add(listItem3);
    vm.DropDownSelectList.Add(listItem4);
    vm.DropDownSelectList.Add(listItem5);
    vm.DropDownSelectList.Add(listItem6);
    vm.DropDownSelectList.Add(listItem7);
}

[HttpPost]
public ActionResult Admin(ChallengesAdminViewModel vm)
{
    if (ModelState.IsValid)//Due to the null dropdownlist  gives model state invalid
    {
    }
}

ViewModel-

public class ChallengesAdminViewModel
{
    [Required]
    public string ApiKey { get; set; }

    [Required]
    public string UserId { get; set; }

    public List<SelectListItem> DropDownSelectList { get; set; }  
}

I dont know why it still requires the list although not required. I want to have only two attributes as required. So I wanted to know how do i declare or change that list to be not required and have my Model State Valid.

A: 

The simple answer would be to remove it from your model and pass it via ViewData instead. Then, your model would contain a member for the value that was selected from the list.

GalacticCowboy
Well..actually that is what i did....but i just wanted to know why it was [required] field even when i didnt set it to be.
Misnomer
Is it possible to do this without "magic strings"?
mxmissile
@mxmissile - have a look at my answer for a *no magic string* version.
Charlino
A: 

I think it's failing because it can't coerce a single value ("") into a SelectListItem to put into a list. You can only ever have one DropDownSelectList value selected.

You might try making your ChallengesAdminViewModel.DropDownSelectList of type string instead. Then it will be the value of the selected option. SelectListItems are made for pushing options to the view, not parsing the posted result.

Jab
+2  A: 

The way I do it is have a property in my view model that the dropdown will be bound to (which is nullable) and then have a separate property that contains all the options for the drop down.

ViewModel properties

public int? CountryId { get; set; }
public IEnumerable<SelectListItem> CountryOptions { get; set; }

View

<label for="CountryId">Country:</label>
<%: Html.DropDownListFor(x => x.CountryId, Model.CountryOptions, "N/A")%>

Note: The "N/A" string is the default empty value.

HTHs,
Charles

Ps. This is of course using ASP.NET MVC 2

Charlino