【问题标题】:MVC 5 Razor view not binding bool to inputMVC 5 Razor 视图未将 bool 绑定到输入
【发布时间】:2013-12-10 15:29:00
【问题描述】:

我有一个 razor 视图(Framework 4.5,MVC 5)和一个 html 输入 type=checkbox,其值等于模型布尔值,但它绑定“值”而不是 true 或 false。

这是我的代码:

for (int index = 0; index < Model.Item1.Locations.Length; index++)
        {
            WSTupleOfInt32StringStringBoolean location = Model.Item1.Locations[index];
                <div class="editor-field">
                    <input id="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].Key", index, Model.Item2)" type="checkbox" value="@location.ThirdValue" name="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].ThirdValue", index, Model.Item2)" />
                </div>
                <div class="editor-label">
                    <label for="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].Key", index, Model.Item2)">@location.FirstValue</label>
                    @if (!string.IsNullOrEmpty(location.SecondValue))
                    {
                        <a href="@string.Format("//maps.google.com/?q={0}", location.SecondValue)" target="_blank"><img alt="@location.SecondValue" src="@string.Format("//maps.google.com/maps/api/staticmap?center={0}&markers=color:blue|{0}&zoom=15&size=64x64&sensor=false", location.SecondValue)" /></a>
                    }
                </div><br />
        }

location.ThirdValue 是布尔属性,调试属性没问题.. 但在 HTML 中我得到value="value" 而不是value="false"

发生了什么事?

【问题讨论】:

    标签: c# html asp.net-mvc asp.net-mvc-4 razor


    【解决方案1】:

    看到这个Answer

    基本上你想用HTML.CheckBoxFor(model =&gt; model.booleanProperty)

    【讨论】:

    • 在我的模型上,我有 public bool NewContact { get; '内部'设置;这使得“NewContact”即使使用 CheckboxFor 也总是错误的。删除内部,这有效。赞成。
    【解决方案2】:

    这样做

    <input id="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].Key", index, Model.Item2)" type="checkbox" @(location.ThirdValue ? "checked" : "") name="@string.Format("presentation.ServiceInfoes[{1}].Locations[{0}].ThirdValue", index, Model.Item2)" />
    

    该值未设置复选框是否选中,值具有不同的功能。例如,如果您将 value 设置为 'test' 并选中复选框,当您提交表单时,您会看到提交的变量的值将是 'test',而不是 true;

    你可以用它做一些很酷的事情。例如,您的表单上有 3 个复选框。它们都具有相同的名称,但值不同。当您提交表单时,您得到的结果将是逗号分隔的字符串,带有选中复选框的值;

    【讨论】:

      猜你喜欢
      • 2016-04-15
      • 1970-01-01
      • 2016-11-16
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 2016-04-22
      相关资源
      最近更新 更多