gpt4 book ai didi

asp.net - @Html.DropDownList Razor View 中的问题?

转载 作者:行者123 更新时间:2023-12-01 10:56:59 25 4
gpt4 key购买 nike

我有一个响应提交按钮的表单。

我的菜单下拉列表如下:

@Html.DropDownList("State", new List<SelectListItem>
{
new SelectListItem { Text = "Please select" },
new SelectListItem { Value = "AL", Text="Alabama" }, ....
new SelectListItem { Value = "WY", Text="Wyoming" })

如何在我的模型中将所选值作为 bool 值或最好作为字符串..

我需要验证

[Required(ErrorMessage = "Please select a state.")]
public string/bool State { get; set; }

请帮忙。

谢谢

最佳答案

How can I get the selected value as bool

将状态名称绑定(bind)到 bool 变量几乎没有意义。

改用字符串:

public class MyViewModel
{
[Required(ErrorMessage = "Please select a state.")]
public string State { get; set; }
}

然后你可以有一个 Controller :

public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// there was a validation error - probably the user didn't select a state
// => redisplay the view so that he can fix the error
return View(model);
}

// at this stage the model is valid
// you could use the model.State property that will hold the selected value
return Content("Thanks for selecting state: " + model.State);
}
}

最后你会得到一个相应的强类型 View :

@model MyViewModel
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.State)
@Html.DropDownListFor(
x => x.State,
new[]
{
new SelectListItem { Text = "Please select" },
new SelectListItem { Value = "AL", Text="Alabama" },
.....
new SelectListItem { Value = "WY", Text="Wyoming" }
},
"-- select a state --"
)
@Html.ValidationMessageFor(x => x.State)
</div>
<button type="submit">OK</button>
}

关于asp.net - @Html.DropDownList Razor View 中的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14628034/

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