我有一个单选按钮列表在我的创建视图。当选择下拉菜单时,它会与复选框一起生成。
@model IEnumerable<Admin.Models.viewmodel>
@foreach (var item in Model)
{
<label>
@Html.CheckBox("User", item.Selected, new { @id = "User" + item.Value, @value = item.Value })
@item.Text
</label>
<label>
@Html.RadioButton("rdnUser" + item.Value.TrimStart(), 1, item.IsSelected,new { @id = "rdnUser"})Primary
</label>
<label>
@Html.RadioButton("rdnUser" + item.Value.TrimStart(), 2,item.IsSelected, new { @id = "rdnUser"})Secondary
</label>
}
我将单选按钮的值保存到表UserMapping中的UserType字段。
当我点击编辑链接时,我想根据数据库值选择单选按钮。
创建一个视图模型来获取复选框和单选按钮中的值。Viewpartial视图模型为:-
public class viewpartial : System.Web.Mvc.SelectListItem
{
public int Values { get; set; }
public bool IsSelected { get; set; }
}
查询为:-
var query = (from u in UserMapping
where u.UserID == id && u.Active == 1
join f in Financial on u.FinancialID equals f.FinancialID
into c
from d in c.DefaultIfEmpty()
select new viewpartialIFC
{
Text = d.FiName,
Value = SqlFunctions.StringConvert((double)d.FinancialID),
Selected = d.FinancialID == u.FinancialID ? true : false,
Values = u.UserType,
//IsSelected=???
}).Distinct().ToList();
我应该在查询中做什么更改来获得单选按钮…
这是一种您可以创建用户列表的方式,并拥有选择他们(复选框)和选择特定角色(单选按钮)的选项:
ViewModel:
public class AdminViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool isSelected { get; set; }
public int RadioValue { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var data = GenerateViews();
return View(data);
}
[HttpPost]
public ActionResult Index(IList<AdminViewModel> data)
{
var selectedViews = data.Where(d => d.isSelected == true);
foreach (var selected in selectedViews)
{
//selected.Id;
//selected.RadioValue;
}
System.Diagnostics.Debugger.Break();
return View(data);
}
private IList<AdminViewModel> GenerateViews()
{
var output = new List<AdminViewModel>();
var rand = new Random();
for (var count = 1; count <= 10; ++count)
{
var newView = new AdminViewModel();
newView.Id = count;
newView.Name = "Name " + count.ToString();
newView.isSelected = false;
newView.RadioValue = rand.Next(1, 3);
output.Add(newView);
}
return output;
}
}
视图:
@model IList<WebMVC3.Controllers.AdminViewModel>
<h2>Index</h2>
@using (Html.BeginForm())
{
//foreach (var item in Model)
for(var index = 0; index < Model.Count; ++index)
{
<div>
@Html.HiddenFor(m => Model[index].Id)
<label>
@Html.CheckBoxFor(m => Model[index].isSelected, Model[index].isSelected)
@Model[index].Name
</label>
<label>
@Html.RadioButtonFor(m => Model[index].RadioValue, 1)
Primary
</label>
<label>
@Html.RadioButtonFor(m => Model[index].RadioValue, 2)
Secondary
</label>
</div>
}
<input type="submit" value="Save" />
}