【发布时间】:2016-09-29 20:18:24
【问题描述】:
我有一个编辑器模板Duration,其中包含四个简单的单选按钮。
我正在将此模板用于我的班级Test 的一个属性。
我无法将此属性绑定到单选按钮列表并在加载时选择正确的单选按钮。选择一个值并提交将返回正确的值。
我尝试将单选按钮的值更改为各种不同的值,但无济于事。
我应该将什么值传递给RadioButtonFor 才能使其正常工作?
理想情况下,此编辑器模板采用可为空的浮点数并且仍然有效。
Duration.cshtml
@model float
<h3>Model Value: @Model</h3>
@Html.RadioButtonFor(model => model, 0.25F, new { id = "btnQuarterDay" }) @(.25F)
@Html.RadioButtonFor(model => model, 0.5F, new { id = "btnHalfDay" }) @(.5F)
@Html.RadioButtonFor(model => model, 0.75F, new { id = "btnThreeQuarterDay" }) @(.75F)
@Html.RadioButtonFor(model => model, 1.0F, new { id = "btnOneDay" }) @(1.0F)
Test.cs
public class Test
{
[UIHint("Duration")]
[Display(Name = "Days")]
public float Duration { get; set; }
}
HomeController
public class HomeController : Controller
{
public ActionResult Index(float? duration = null)
{
var model = new Test
{
Duration = duration.GetValueOrDefault(1F)
};
return View(model);
}
[HttpPost]
public ActionResult Index(Test model)
{
ViewBag.Success = true;
ViewBag.ValueSelected = model.Duration;
return View(model);
}
}
Index.cshtml
@model RadioButtonForTest.Models.Test
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="row">
<div class="col-md-4">
@Html.EditorFor(model => model.Duration)
@Html.ValidationMessageFor(model => model.Duration)
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
if (ViewBag.Success ?? false)
{
<span>Value Selected:</span> @ViewBag.ValueSelected
}
}
更新:绘图增稠剂
我将 Index 操作连接到持续时间,以便我可以通过查询字符串传递它。如果未通过查询字符串传递值。它将选择下面的单选按钮:
@Html.RadioButton("", Model, Model.Equals(1.0F), new { id = "radbtnOneDay4" })
如果我导航到查询字符串 /Home/Index?duration=.5
未选择任何内容,但在调试 Duration.cshtml Model.Equals(.50F) 时会报告 TRUE。所以我希望这个单选按钮被选中:
@Html.RadioButton("", Model, Model.Equals(.50F), new { id = "radbtnHalfDay4" })
这不是疯了吗?为什么不检查这个单选按钮???这是一个错误吗?是否可以添加自定义模型绑定器来处理浮动?
更新 2
查询字符串参数duration 匹配模型名称,查询字符串覆盖模型值。
当我将参数更改为dur 时,它工作正常。使用以下 URL,它将使用 ViewModel 中的值。
/Home/Index?dur=.5
我知道这背后有充分的理由……但这令人恼火。
【问题讨论】:
-
不确定为什么它不能与您的 EditorTemplate 一起使用,但如果您直接在主视图中包含
@Html.RadioButtonFor(m => m.Duration, 0.25F)等,它会起作用 -
绘图加厚:有时 html 助手用于模型值的内容与调试器显示的内容有所不同。请参阅stackoverflow.com/questions/1775170/… 了解更多信息
标签: c# asp.net-mvc asp.net-mvc-5