开发者

Although not [required] List field shows up as required and Model State is not Valid due to it being 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);
}

[H开发者_如何转开发ttpPost]
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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜