【发布时间】:2021-10-08 05:02:50
【问题描述】:
我想检查从我的Index.cshtml 文件中选择了哪个单选按钮,然后我想使用 switch 语句为其对象设置属性。我正在阅读如何执行此操作,但其中大多数是针对 Windows 窗体中的组,但这不适用于我,因为我使用的是 asp.net core 5.0 web mvc 项目。
在我的Index.cshmtl 我有以下内容:
....
<form action="@Url.Action("SecIndex", "Second")">
<input type="radio" value="1" /><label>Valid</label>
<input type="radio" value="2" /><label>Wrong</label>
<input type="radio" value="3" /><label>InValid</label>
<input type="submit" value="Address Validation" />
</form>
然后在我的HomeController,我有以下方法:
[HttpPost]
public IActionResult ValidateAddress()
{
// if radio button was checked, perform the following var request.
var check = ""; // this should be able to grab the label of the button that was selected
switch (check)
{
case "Valid":
var request = new AddressRequest
{
StatusCode = 1,
Address = "2018 Main St New York City, NY, 10001"
};
break;
case "Wrong":
var req = new AddressRequest
{
StatusCode = 2,
Address = "91 Apple City Galveston, TX, 77550"
};
break;
case "Invalid":
var addressRequest = new AddressRequest
{
StatusCode = 3,
Address = "00000 Tree Ln, Miami FL 91041"
};
break;
}
return View();
}
但我似乎无法弄清楚如何允许变量 check 执行检查以查看选择了哪个单选按钮,因为这是一个 asp.net core 5.0 web mvc 项目而不是 Windows 窗体。有没有办法在这种类型的项目中做到这一点?
更新:
所以我意识到我希望拥有与以前一样的价值与数字。所以实现这个建议,我仍然需要将用户重定向到我的Second 控制器中的SecIndex 方法。但是,我仍然需要获取选中的单选按钮的值。所以我尝试做return RedirectToAction("SecIndex");,但是当我运行程序并点击按钮来验证它给了我:
此页面无法正常工作。如果问题仍然存在,请联系网站所有者。 HTTP 错误 405
我做错了什么吗? URI 显示为https://localhost:5443/Home/ValidateAddress?Status=1。不是我选择了第一个选项,它应该给我状态为 1。不知道为什么它会返回。
在我的HomeController里面:
[HttpPost]
public IActionResult ValidateAddress(string validate)
{
// if radio button was checked, perform the following var request.
switch (validate)
{
case "Valid":
var request = new AddressRequest
{
StatusCode = 1,
Address = "2018 Main St New York City, NY, 10001"
};
break;
case "Wrong":
var req = new AddressRequest
{
StatusCode = 2,
Address = "91 Apple City Galveston, TX, 77550"
};
break;
case "Invalid":
var addressRequest = new AddressRequest
{
StatusCode = 3,
Address = "00000 Tree Ln, Miami FL 91041"
};
break;
}
return RedirectToAction("SecIndex");
}
}
Home View... index.cshtml:
<form action="@Url.Action("ValidateAddress", "Home")">
<input type="radio" value="1" name="Status"/><label>Valid</label>
<input type="radio" value="2" name="Status"/><label>Wrong</label>
<input type="radio" value="3" name="Status"/><label>InValid</label>
<input type="submit" value="Address Validation" />
</form>
【问题讨论】:
-
SecIndex 动作被 [HttpPost] 过滤器覆盖?
-
第一个 SecIndex 没有 [HttpPost] 过滤器,但第二个有。我会在帖子中分享。请查看更新后的帖子@MeysamaAsadi
-
是否可以输入SecIndex动作码?
-
对不起,你到底是什么意思?
-
这成功了!谢谢!我看到 Index.cshtml 现在已经发布了它的操作
标签: c# html asp.net-mvc asp.net-core-mvc radio-button