asp.net-mvc - 将选定的单选按钮值传递给控制器 C# MVC
问题描述
我有一个显示客户 ID、客户名称和单选按钮循环的表格。我正在尝试根据我表上给出的选项链接登录的用户。
电子邮件:test@gmail.com
客户 ID | 客户名称 | 选择用户
第1234章 测试 1 | 单选按钮(选中)
第2345章 测试 2 | 单选按钮
我想要的是,如果选中了单选按钮(即 custId:1234),我想获取该 CustID。
这是我的代码:
控制器
public ActionResult AddCustomerLinkToDB(string IsSeleted)
{
string selectedCustomer = IsSeleted;
return View();
}
cshtml
@using (Html.BeginForm("AddCustomerLinkToDB", "Admin", FormMethod.Post))
{
<table class="table table-bordered table-hover">
<tr>
<th>Customer ID</th>
<th>Customer Name</th>
<th>Select this user</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@Html.RadioButton("IsSelected", new { id = item.Id })</td>
</tr>
}
</table>
}
解决方案
string
您可以尝试创建一个既存储选定值又存储单选按钮项目的视图模型,而不是传递单个参数。这是正确视图模型设置的示例:
public class ViewModel
{
// since the CustID is numeric, I prefer using 'int' property
public int IsSelected { get; set; }
public List<Customer> Customers { get; set; }
// other properties
}
RadioButtonFor
通过使用绑定IsSelected
属性,视图页面应如下所示:
@model ViewModel
@using (Html.BeginForm("AddCustomerLinkToDB", "Admin", FormMethod.Post))
{
<table class="table table-bordered table-hover">
<tr>
<th>Customer ID</th>
<th>Customer Name</th>
<th>Select this user</th>
</tr>
@foreach (var item in Model.Customers)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@Html.RadioButtonFor(model => model.IsSelected, item.Id, new { id = item.Id })</td>
</tr>
}
</table>
}
最后,应调整控制器参数以接受 viewmodel 类,如下所示:
[HttpPost]
public ActionResult AddCustomerLinkToDB(ViewModel model)
{
int selectedCustomer = model.IsSelected;
// other stuff
return View();
}
通过使用此设置,选定的值将IsSelected
在表单提交期间存储在属性中。
推荐阅读
- xamarin.ios - 在win10上开发Xamarin不再需要Visual Studio 2019?
- php - laravel eloquent 如何获得区域的财务平衡
- kubernetes - 通过集群外的 pod IP 访问 pod 应用
- javascript - Microsoft.AspNetCore.Mvc.ViewFeatures.UnsupportedJavaScriptRuntime
- c# - Selenium - 等到元素存在、可见且可交互,即使在 C# 中的可滚动模式上也是如此
- android - Koin 在片段与其宿主活动之间的 SharedViewModel
- vue.js - BootstrapVue 组件未转换为 HTML
- mysql - Laravel 使用 where 和多个 whereHas
- get - 在 Raku 中使用 get/prompt gettig 后如何清除 stdin ($*IN) 上的 EOF?
- tfs - 更改文件的构建操作不会更改 .csproj