2

我想将文本框设置为只读,如果它在 MVC 中具有价值。

所以我写

 <tr>
 @if (model.first_name != "" ) { 
   <td >
                @Html.LabelFor(model => model.first_name):
            </td>
            <td >
                @Html.TextBoxFor(model => model.first_name)
                <span class="required">*</span>
                @Html.ValidationMessageFor(model => model.first_name)
            </td>
@ else  
  <td >
  @Html.LabelFor(model => model.first_name):
            </td>
            <td >
                @Html.EditorFor(model => model.first_name)
                <span class="required">*</span>
                @Html.ValidationMessageFor(model => model.first_name)
            </td>
@}

            <td >
                @Html.LabelFor(model => model.first_name):
            </td>
            <td >
                @Html.EditorFor(model => model.first_name)
                <span class="required">*</span>
                @Html.ValidationMessageFor(model => model.first_name)
            </td>
        </tr>

但是它不起作用..如何解决它?我该怎么做??

4

3 回答 3

3

您可以将字段readonly="readonly"而不是disabled="disabled"只读字段值提交给服务器,同时用户仍不可编辑。

于 2012-11-06T02:11:28.160 回答
3

您可以修改您的视图模型,如下所示

public class MyViewModel
{
  public string first_name { get; set; }

  public object first_name_attributes
  {
    get
    {
      return string.IsNullOrEmpty(first_name) ? null : new { @readonly = "readonly" };
    }
  }
}

然后,您可以在您的 UI 中以声明方式添加对象。

Html.TextBoxFor(x => x.first_name, first_name_attributes)

这导致 UI 更简单,并且视图模型具有可单元测试的优势!

于 2012-11-06T02:14:28.890 回答
1

在 razor 中创建一个 if 语句,并在要禁用的输入/编辑器上设置一个 disabled = "disabled"。

@if
(model.first_name != null)
{

   <td >
            @Html.LabelFor(model => model.first_name):
        </td>
        <td >
            @Html.TextBoxFor(model => model.first_name)
            <span class="required">*</span>
            @Html.ValidationMessageFor(model => model.first_name)
        </td>
}
else
{
  <td >
  @Html.LabelFor(model => model.first_name):
        </td>
        <td >
            @Html.EditorFor(model => model.first_name, new { disabled = "disabled", @readonly = "readonly" }))
            <span class="required">*</span>
            @Html.ValidationMessageFor(model => model.first_name)
        </td>

        <td >
            @Html.LabelFor(model => model.first_name):
        </td>
        <td >
            @Html.EditorFor(model => model.first_name)
            <span class="required">*</span>
            @Html.ValidationMessageFor(model => model.first_name)
        </td>
    </tr>

}

于 2012-11-06T01:57:51.287 回答