Although not required [required], the list box is displayed as needed, and the state of the model is not valid because it is null?

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 do not know why he still needs a list, although this is not required. I want to have only two attributes as needed. Therefore, I wanted to know how I declare or modify this list so that it is not required, and that my model state is valid.

+3
source share
3 answers

, , , ( NULL), , .

ViewModel

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

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

. "N/A" .

HTHS,

Ps. , , ASP.NET MVC 2

+6

ViewData. , .

0

, , ("") SelectListItem . DropDownSelectList.

ChallengesAdminViewModel.DropDownSelectList . . SelectListItems , .

0
source

Source: https://habr.com/ru/post/1745168/


All Articles