gpt4 book ai didi

asp.net-mvc - 虽然不是[必需]列表字段按要求显示,但模型状态由于为空而无效?

转载 作者:行者123 更新时间:2023-12-02 16:09:37 25 4
gpt4 key购买 nike

我有以下代码-

查看-

<% 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
{
}
}

View 模型-

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

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

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

我不知道为什么它仍然需要列表,尽管不是必需的。我只想根据需要拥有两个属性。所以我想知道如何声明或更改该列表为不需要的并使我的模型状态有效。

最佳答案

我这样做的方法是在我的 View 模型中有一个属性,下拉列表将绑定(bind)到该属性(可以为空),然后有一个单独的属性,其中包含下拉列表的所有选项。

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” 字符串是默认的空值。

HTH,
查尔斯

诗。这当然是使用 ASP.NET MVC 2

关于asp.net-mvc - 虽然不是[必需]列表字段按要求显示,但模型状态由于为空而无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2822504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com