我有一个显示客户ID,客户名称和单选按钮循环的表。我正在尝试根据表上给出的选项链接登录的用户。
电子邮件:test@gmail.com
CustID |客户名称| SelectUser
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>
}
答案 0 :(得分:1)
您可以尝试创建一个同时存储选定值和单选按钮项的视图模型,而不是传递单个string
参数。这是正确的viewmodel设置示例:
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
属性中。